package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.lamp.care.common.CareCommonUtil;
import top.tangyh.lamp.care.entity.*;
import top.tangyh.lamp.care.mapper.*;
import top.tangyh.lamp.care.service.*;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.lamp.care.manager.BCareRecordsConfigNewManager;
import top.tangyh.lamp.care.vo.query.CareRecordQueryDto;
import top.tangyh.lamp.care.vo.query.IoItemQueryParam;
import top.tangyh.lamp.care.vo.result.*;
import top.tangyh.lamp.care.vo.save.*;
import top.tangyh.lamp.care.vo.update.BCareRecordsConfigNewUpdateVO;
import top.tangyh.lamp.care.vo.query.BCareRecordsConfigNewPageQuery;
import top.tangyh.lamp.care.vo.update.CareRecordsConfigUpdateVO;
import top.tangyh.lamp.common.constant.CommonConstant;
import top.tangyh.lamp.common.constant.EventEnum;
import top.tangyh.lamp.common.constant.ModelItemConstant;
import top.tangyh.lamp.common.utils.ConvertUtil;
import top.tangyh.lamp.common.utils.PDateUtils;
import top.tangyh.lamp.common.utils.YDateUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 新版本护理记录表单配置表
 * </p>
 *
 * @author zqb
 * @date 2024-08-05 15:12:19
 * @create [2024-08-05 15:12:19] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class BCareRecordsConfigNewServiceImpl extends SuperServiceImpl<BCareRecordsConfigNewManager, Long, BCareRecordsConfigNew> implements BCareRecordsConfigNewService {


    private final BCareRecordsConfigNewMapper bCareRecordsConfigNewMapper;


    private final BCareRecordService bCareRecordService;


    private final BIoRecordService bIoRecordService;

    private final BObsvRecordService bObsvRecordService;


    private final BCareContentService bCareContentService;


    private final BPgRecordService bPgRecordService;


    private final BIoRecordMapper bIoRecordMapper;

    private final BCarePgVteService bCarePgVteService;


    private final BObsvRecordMapper bObsvRecordMapper;


    private final BPgpfMapper bPgpfMapper;

    private final BHl7EventMapper bHl7EventMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveCareRecordsConfigNew(CareRecordsConfigSaveVO vo) {
        BCareRecordsConfigNew po = ConvertUtil.convert(vo, BCareRecordsConfigNew.class);
        //保存父级数据信息
        bCareRecordsConfigNewMapper.insert(po);
        List<CareRecordsConfigSaveVO> list_sun = vo.getChildNode();
        list_sun.forEach(e -> {
            e.setPid(po.getId());
        });
        List<BCareRecordsConfigNew> list_po;
        list_po = ConvertUtil.convertList(list_sun, BCareRecordsConfigNew.class);
        //保存子级数据信息
        this.saveBatch(list_po);
        return po.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatchCareRecordsConfigNew(List<CareRecordsConfigSaveVO> vos) {
        traversingSave(vos);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchUpdateCareRecordsConfigNew(List<CareRecordsConfigUpdateVO> listVo) {
        return traversingUpdate(listVo);
    }


    @Override
    public List<BCareRecordsConfigNew> getIdObjectByPid(Long pid) {

        return bCareRecordsConfigNewMapper.getIdObjectByPid(pid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<BatchResult> updateBatchById(List<BCareRecordsConfigNew> list) {
        return bCareRecordsConfigNewMapper.updateById(list);
    }

    @Override
    public List<BCareRecordsConfigNewResultVO> listCareRecordsConfig() {
        LambdaQueryWrapper<BCareRecordsConfigNew> queryWrapper = new LambdaQueryWrapper<>();
        List<BCareRecordsConfigNew> list = bCareRecordsConfigNewMapper.selectList(queryWrapper);
        List<BCareRecordsConfigNewResultVO> listResult = ConvertUtil.convertList(list, BCareRecordsConfigNewResultVO.class);
        return listResult;
    }

    /**
     * 递归更新
     *
     * @param root
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer traversingUpdate(List<CareRecordsConfigUpdateVO> root) {
        Integer rows = 0;
        for (CareRecordsConfigUpdateVO node : root) {
            BCareRecordsConfigNew po = ConvertUtil.convert(node, BCareRecordsConfigNew.class);
            rows = bCareRecordsConfigNewMapper.updateById(po);

            List<CareRecordsConfigUpdateVO> childres = node.getChildNode();
            if (childres != null && childres.size() > 0) {
                traversingUpdate(childres);
            }
        }
        return rows;
    }

    /**
     * 递归保存
     *
     * @param root
     * @return
     */
    public Integer traversingSave(List<CareRecordsConfigSaveVO> root) {
        Integer rows = 0;
        for (CareRecordsConfigSaveVO node : root) {
            BCareRecordsConfigNew po = ConvertUtil.convert(node, BCareRecordsConfigNew.class);
            rows = bCareRecordsConfigNewMapper.insert(po);

            List<CareRecordsConfigSaveVO> childres = node.getChildNode();
            if (childres != null && childres.size() > 0) {
                childres.forEach(e -> {
                    e.setPid(po.getId());
                });
                traversingSave(childres);
            }
        }
        return rows;
    }

    @Override
    public List<BCareRecordsConfigNewResultVO> getAllcareConfig() {
        List<BCareRecordsConfigNewResultVO> list = bCareRecordsConfigNewMapper.noteTreeNew();
        return list;
    }

    @Override
    public List<BCareRecordsConfigNewResultVO> titleNoteTreeNew(String patientIdent, String hospitalNumber, BHl7Event yxHl7EventPORk) {
        List<BCareRecordsConfigNewResultVO> listCareRecordsConfigOutVO = bCareRecordsConfigNewMapper.noteTreeNew();
        if (null == patientIdent) {
            return listCareRecordsConfigOutVO;
        }
        Map<String, CareItemVO> hlczMap = bCareRecordService.itemQueryByPatientIdent(patientIdent);
        IoItemQueryParam ioItemQueryParam = new IoItemQueryParam();
        ioItemQueryParam.setPatientIdent(patientIdent);
        ioItemQueryParam.setModelCode("crl-in");
        List<IoItemVO> ioin = bIoRecordService.itemQuery(ioItemQueryParam);
        if (null == ioin) {
            ioin = new ArrayList<>();
        }
        ioItemQueryParam = new IoItemQueryParam();
        ioItemQueryParam.setPatientIdent(patientIdent);
        ioItemQueryParam.setModelCode("crl-out");
        List<IoItemVO> ioout = bIoRecordService.itemQuery(ioItemQueryParam);
        if (null == ioout) {
            ioout = new ArrayList<>();
        }
        CareConfigVO config = new CareConfigVO();
        config.setHlcz(hlczMap);
        config.setIoin(ioin);
        config.setIoout(ioout);
        //添加用于修改和新增数据需要的配置
        for (BCareRecordsConfigNewResultVO item : listCareRecordsConfigOutVO) {
            if (StrUtil.isEmpty(item.getDictValue())) {
                initConfig(item, config);
            }
        }
        return listCareRecordsConfigOutVO;
    }

    private void initConfig(BCareRecordsConfigNewResultVO item, CareConfigVO config) {
        if (StrUtil.isNotEmpty(item.getDictValue()) && item.getDictValue().equals("yx-hlcz")) {
            if (CollectionUtil.isNotEmpty(config.getHlcz()) && CollectionUtil.isNotEmpty(item.getChildNode())) {
                for (BCareRecordsConfigNewResultVO sub : item.getChildNode()) {
                    initHlczConfig(sub, config.getHlcz());
                }
            }
        } else if (StrUtil.isNotEmpty(item.getDictValue()) && item.getDictValue().equals("yx-crl-in")) {
            if (CollectionUtil.isNotEmpty(config.getIoin())) {
                item.setEnumMap(JSONObject.toJSONString(config.getIoin()));
            }

        } else if (StrUtil.isNotEmpty(item.getDictValue()) && item.getDictValue().equals("yx-crl-out")) {
            if (CollectionUtil.isNotEmpty(config.getIoout())) {
                item.setEnumMap(JSONObject.toJSONString(config.getIoout()));
            }
        } else {
            if (CollectionUtil.isNotEmpty(item.getChildNode())) {
                for (BCareRecordsConfigNewResultVO sub : item.getChildNode()) {
                    initConfig(sub, config);
                }
            }
        }
    }

    private void initHlczConfig(BCareRecordsConfigNewResultVO item, Map<String, CareItemVO> hlcz) {
        if (StrUtil.isNotEmpty(item.getDictValue())) {
            CareItemVO care = hlcz.get(item.getItemCode());
            if (null != care) {
                item.setEnumMap(JSONObject.toJSONString(care));
            }
        }
        if (CollectionUtil.isNotEmpty(item.getChildNode())) {
            for (BCareRecordsConfigNewResultVO sub : item.getChildNode()) {
                initHlczConfig(sub, hlcz);
            }
        }
    }


    @Override
    public List<Map.Entry<String, List<Map>>> listOfDataNew(String patientIdent, String hospitalNumber, Long startTime, Long endTime) {
        //查询入科时间和出院时间(如果出院时间为null则取当前时间 )
        //查找入科消息 得到入科时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        BHl7Event yxHl7EventPO_cy = bHl7EventMapper.selectOneByEventTypeHospitalNumber(EventEnum.CY.getEventType(), hospitalNumber);
//        LocalDateTime cyTime = yxHl7EventPO_cy.getEventTime();
//        if (null == cyTime) {
//            cyTime = LocalDateTime.now();
//        }


        //查询数据源类型的标题
        LambdaQueryWrapper<BCareRecordsConfigNew> wrapperCareRecordsConfig = new LambdaQueryWrapper<>();
        wrapperCareRecordsConfig.eq(BCareRecordsConfigNew::getIsDeleted, 0);
        wrapperCareRecordsConfig.eq(BCareRecordsConfigNew::getTitleType, 1);

        List<BCareRecordsConfigNew> listCareRecordsConfig = this.list(wrapperCareRecordsConfig);

        List<BCareRecordsConfigNew> uniqueDictValues = listCareRecordsConfig.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(o -> o.getDictValue()))), ArrayList::new)
        );
        //需要查询的模块集合
        List<String> collectDictValue = uniqueDictValues.stream().map(BCareRecordsConfigNew::getDictValue).collect(Collectors.toList());

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        //算出最早的 有数据的时间
//        String rkTimeStr = DateUtil.formatDateTime(yxHl7EventPORk.getEventTime());
//        String cyTimeStr = DateUtil.formatDateTime(cyTime);

        //开始时间
        String startTimeStr = DateUtil.formatDateTime(new Date(startTime));
        //结束时间
        String endTimeStr = "";
        if (null != endTime) {
            endTimeStr = DateUtil.formatDateTime(new Date(endTime));
        } else {
            Date dateNow = new Date();
            endTimeStr = DateUtil.formatDateTime(dateNow);
            endTime = dateNow.getTime();
        }


        String minDate = bCareRecordsConfigNewMapper.getMinRecordTimeByParamNew(hospitalNumber, startTimeStr, endTimeStr, collectDictValue);

        List<Map> ckdata = bObsvRecordService.getCktime(hospitalNumber, startTimeStr, endTimeStr);
        if (CollectionUtil.isNotEmpty(ckdata)) {
            Long creatTime = (Long) ckdata.get(0).get("create_time");
            Long mindata1 = YDateUtils.strToDate(minDate, YDateUtils.DATE_TIME_PATTERN).getTime();
            if (creatTime < mindata1) {
                minDate = YDateUtils.dateToStr(new Date(creatTime));
            }
        }

        Map<String, List<Map>> mapData = new ConcurrentHashMap<>(16);
        //寻找有值的 开始时间 (每个模块中至少有个选项有值)
        //先列出来有哪些模块
//        评估评分	yx-pgpf  这期需要
//        观察项	yx-gcx  这期需要
//        出入量	yx-crl  这期需要
//        管道管理	yx-gdgl
//        护理操作	yx-hlcz  这期需要
//        护理交班	yx-hljb
//        护理记录	yx-hljl  这期需要
//        执行用药	yx-zxyy
//        日期时间	date_value
//        操作人员	operater
        List<BObsvRecord> listObsvResult = new ArrayList<>();
        //遍历赋值展示数据
        for (int i = 0; i < collectDictValue.size(); i++) {
            String dictValue = collectDictValue.get(i);
            if (StringUtil.isNotEmpty(dictValue)) {
                //        /*护理记录 数据 */
//        SELECT care_content,record_time from yx_care_content where type=1 and hospital_number='1004409' and record_time between '2021-12-01 09:00:00' and '2022-01-25 14:32:50'
                //先从  护理记录  模块寻找
                if (dictValue.equals(ModelItemConstant.MODEL_HLJL)) {
                    LambdaQueryWrapper<BCareContent> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BCareContent::getType, 1);
                    wrapper.eq(BCareContent::getHospitalNumber, hospitalNumber);
                    wrapper.apply("record_time between '" + minDate + "' and '" + endTimeStr + "'");
                    List<BCareContent> list = bCareContentService.list(wrapper);
                    for (int j = 0; j < list.size(); j++) {
                        BCareContent po = list.get(j);
                        List<Map> mapList = new LinkedList<>();
                        //是否存在相同key 的时间
                        String strRecordTime = list.get(j).getRecordTime().format(dateTimeFormatter);
                        if (mapData.containsKey(strRecordTime + "@" + po.getUpdatedBy())) {
                            //根据这个时间获取 对应key的集合数据
                            List<Map> dataValue = mapData.get(strRecordTime + "@" + po.getUpdatedBy());

                            Map map = new LinkedHashMap();
                            map.put("hljl-careContent", po.getCareContent());
                            map.put("operator", po.getUpdatedBy());
                            map.put("hljl-reocrdId", po.getId());
//                            int width=CareCommonUtil.getStrWidth(po.getCareContent());
//
//                            map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(width),new BigDecimal(jishu),2));
                            map.put("create-time", YDateUtils.getTimestampOfDateTime(po.getCreatedTime()));
                            dataValue.add(map);
                            mapData.put(strRecordTime + "@" + po.getUpdatedBy(), dataValue);
                        } else {

                            Map map = new LinkedHashMap();
                            map.put("hljl-careContent", po.getCareContent());
                            map.put("operator", po.getUpdatedBy());
                            map.put("hljl-reocrdId", po.getId());
//                            int width=CareCommonUtil.getStrWidth(po.getCareContent());
//                            map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(width),new BigDecimal(jishu),2));
                            map.put("create-time", YDateUtils.getTimestampOfDateTime(po.getCreatedTime()));
                            mapList.add(map);
                            mapData.put(strRecordTime + "@" + po.getUpdatedBy(), mapList);
                        }

                    }

                    //评估评分
                } else if (dictValue.equals(ModelItemConstant.MODEL_PGPF)) {
                    //        /*评估评分 数据 */
//        SELECT grade_time,pg_id,show_value from yx_pg_record where hospital_number='1004409' and grade_time between '2021-12-01 09:00:00' and '2022-01-25 14:32:50'
                    LambdaQueryWrapper<BCareRecordsConfigNew> wrapperConfig = new LambdaQueryWrapper<>();
                    wrapperConfig.eq(BCareRecordsConfigNew::getDictValue, "yx-pgpf");
                    wrapperConfig.eq(BCareRecordsConfigNew::getIsDeleted, 0);
                    List<BCareRecordsConfigNew> listConfig = bCareRecordsConfigNewMapper.selectList(wrapperConfig);
                    List<Long> pgIdList = listConfig.stream()
                            .map(BCareRecordsConfigNew::getPgId).distinct()
                            .collect(Collectors.toList());

                    //只查询配置的那些评估评分记录
                    LambdaQueryWrapper<BPgRecord> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BPgRecord::getHospitalNumber, hospitalNumber);
                    wrapper.in(CollectionUtil.isNotEmpty(pgIdList),BPgRecord::getPgId, pgIdList);
                    wrapper.apply("grade_time between '" + minDate + "' and '" + endTimeStr + "'");
                    List<BPgRecord> list = bPgRecordService.list(wrapper);


                    //		SELECT * from yx_care_records_config where dict_value='yx-pgpf' and is_deleted=0

                    for (int j = 0; j < list.size(); j++) {
                        BPgRecord po = list.get(j);

                        List<Map> mapList = new LinkedList<>();

                        String timeStr = DateUtil.format(list.get(j).getGradeTime(), "yyyy-MM-dd HH:mm:ss");
                        //是否存在相同key 的时间
                        if (mapData.containsKey(timeStr + "@" + po.getUpdatedBy())) {
                            List<Map> data_value = mapData.get(timeStr + "@" + po.getUpdatedBy());

                            Map map = new LinkedHashMap();
                            map.put("pgpf-pgId", po.getPgId());
                            map.put("pgpf-type", po.getPgType());
                            map.put("pgpf-showValue", po.getShowValue());
                            map.put("pgpf-reocrdId", po.getId());

//                            int contentWidth=CareCommonUtil.getStrWidth(po.getShowValue());
//                            map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));

                            map.put("operator", po.getUpdatedBy());
                            data_value.add(map);

                            mapData.put(timeStr + "@" + po.getUpdatedBy(), data_value);
                        } else {

                            Map map = new LinkedHashMap();
//
                            map.put("pgpf-pgId", po.getPgId());
                            map.put("pgpf-type", po.getPgType());
                            map.put("pgpf-showValue", po.getShowValue());
                            map.put("pgpf-reocrdId", po.getId());

//                            int contentWidth=CareCommonUtil.getStrWidth(po.getShowValue());
//                            map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));

                            map.put("operator", po.getUpdatedBy());
                            mapList.add(map);
                            mapData.put(timeStr + "@" + po.getUpdatedBy(), mapList);
                        }
                    }
                    //        /*观察项. 数据 */
//        SELECT from_unixtime(rec_time/1000, '%Y-%m-%d %H:%i:%S') rec_time,obsv_code,prop_value from yx_obsv_record  where hospital_number='1004409' and
//        from_unixtime(rec_time/1000, '%Y-%m-%d %H:%i:%S')  between '2021-12-01 09:00:00' and '2022-01-25 14:32:50'        and is_deleted=0
                } else if (dictValue.equals(ModelItemConstant.MODEL_GCX)) {

                    LambdaQueryWrapper<BObsvRecord> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BObsvRecord::getHospitalNumber, hospitalNumber);
                    wrapper.eq(BObsvRecord::getIsDeleted, 0);
                    wrapper.apply("from_unixtime(rec_time/1000, '%Y-%m-%d %H:%i:%S') between '" + minDate + "' and '" + endTimeStr + "'");
                    List<BObsvRecord> list = bObsvRecordService.list(wrapper);


                    for (int j = 0; j < list.size(); j++) {
                        BObsvRecord po = list.get(j);

                        String timeStr = DateUtil.format(new Date(list.get(j).getRecTime()), "yyyy-MM-dd HH:mm:ss");

                        List<Map> mapList = new LinkedList<>();

                        //是否存在相同key 的时间
                        if (mapData.containsKey(timeStr + "@" + po.getUpdatedBy())) {
                            List<Map> data_value = mapData.get(timeStr + "@" + po.getUpdatedBy());

                            Map map = new LinkedHashMap();
                            if (StringUtil.isNotEmpty(po.getCreateSource())) {
                                if (po.getCreateSource().equals("dev")) {
                                    map.put("gcx-obsvCode", po.getObsvCode());
                                    map.put("gcx-propValue", po.getPropValue());
                                    map.put("operator", po.getCaijiren());
                                    map.put("create-time", PDateUtils.getTimestampOfDateTime(po.getCreatedTime()));
                                } else if (po.getCreateSource().equals("hand")) {
                                    map.put("gcx-obsvCode", po.getObsvCode());
                                    map.put("gcx-propValue", po.getPropValue());
                                    map.put("operator", po.getUpdatedBy());
                                    map.put("create-time", PDateUtils.getTimestampOfDateTime(po.getCreatedTime()));
                                }
                            } else {
                                map.put("gcx-obsvCode", po.getObsvCode());
                                map.put("gcx-propValue", po.getPropValue());
                                map.put("operator", po.getUpdatedBy());
                                map.put("create-time", PDateUtils.getTimestampOfDateTime(po.getCreatedTime()));
                            }
                            data_value.add(map);

                            mapData.put(timeStr + "@" + po.getUpdatedBy(), data_value);
                        } else {

                            Map map = new LinkedHashMap();
//                            map.put("gcx-obsvCode", po.getObsvCode());
//                            map.put("gcx-propValue", po.getPropValue());
                            if (StringUtil.isNotEmpty(po.getCreateSource())) {
                                if (po.getCreateSource().equals("dev")) {
                                    map.put("gcx-obsvCode", po.getObsvCode());
                                    map.put("gcx-propValue", po.getPropValue());
                                    map.put("operator", po.getCaijiren());
                                    map.put("create-time", PDateUtils.getTimestampOfDateTime(po.getCreatedTime()));
                                } else if (po.getCreateSource().equals("hand")) {
                                    map.put("gcx-obsvCode", po.getObsvCode());
                                    map.put("gcx-propValue", po.getPropValue());
                                    map.put("operator", po.getUpdatedBy());
                                    map.put("create-time", PDateUtils.getTimestampOfDateTime(po.getCreatedTime()));
                                }
                            } else {
                                map.put("gcx-obsvCode", po.getObsvCode());
                                map.put("gcx-propValue", po.getPropValue());
                                map.put("operator", po.getUpdatedBy());
                                map.put("create-time", PDateUtils.getTimestampOfDateTime(po.getCreatedTime()));
                            }
                            mapList.add(map);

                            mapData.put(timeStr + "@" + po.getUpdatedBy(), mapList);
                        }
                    }


                    //        /*出入量 数据*/
//        SELECT model_code,item_code,io_value,time  from yx_io_record where time between '2021-12-01 09:00:00' and '2022-01-25 14:32:50'
//        and hospital_number='1004409' ORDER BY time
                } else if (dictValue.equals(ModelItemConstant.MODEL_CRL)) {
                    LambdaQueryWrapper<BIoRecord> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BIoRecord::getHospitalNumber, hospitalNumber);
                    wrapper.eq(BIoRecord::getIsShowCare, CommonConstant.YES_NUMBER);
                    wrapper.apply("real_time between '" + minDate + "' and '" + endTimeStr + "'");
                    List<BIoRecord> list = bIoRecordService.list(wrapper);
                    for (int j = 0; j < list.size(); j++) {
                        BIoRecord po = list.get(j);

                        String timeStr = list.get(j).getRealTime().format(dateTimeFormatter);
                        List<Map> mapList = new LinkedList<>();
                        if (mapData.containsKey(timeStr + "@" + po.getUpdatedBy())) {
                            List<Map> dataValue = mapData.get(timeStr + "@" + po.getUpdatedBy());

                            Map map = new LinkedHashMap();
                            map.put("crl-modelCode", po.getModelCode());
                            map.put("crl-itemCode", po.getItemCode());
                            map.put("crl-ioValue", po.getIoValue());
                            map.put("crl-recordId", po.getId());
//                            int contentWidth=CareCommonUtil.getStrWidth(po.getIoValue());
//                            map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));

                            map.put("operator", po.getUpdatedBy());
                            dataValue.add(map);

                            mapData.put(timeStr + "@" + po.getUpdatedBy(), dataValue);
                        } else {

                            Map map = new LinkedHashMap();

                            map.put("crl-modelCode", po.getModelCode());
                            map.put("crl-itemCode", po.getItemCode());
                            map.put("crl-ioValue", po.getIoValue());
                            map.put("crl-recordId", po.getId());
//                            int contentWidth=CareCommonUtil.getStrWidth(po.getIoValue());
//                            map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));
                            map.put("operator", po.getUpdatedBy());
                            mapList.add(map);

                            mapData.put(timeStr + "@" + po.getUpdatedBy(), mapList);
                        }

                    }
                    //        /*护理操作 数据*/
//        SELECT from_unixtime(mapped_time/1000, '%Y-%m-%d %H:%i:%S') mapped_time,item_value,item_code from yx_care_record
//        where hospital_number='1004409' and   from_unixtime(mapped_time/1000, '%Y-%m-%d %H:%i:%S')  between '2021-12-01 09:00:00' and '2022-01-25 14:32:50'
                } else if (dictValue.equals(ModelItemConstant.MODEL_HLCZ)) {
                    LambdaQueryWrapper<BCareRecord> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BCareRecord::getHospitalNumber, hospitalNumber);
                    wrapper.apply("from_unixtime(mapped_time/1000, '%Y-%m-%d %H:%i:%S') between '" + minDate + "' and '" + endTimeStr + "'");


                    List<BCareRecord> list = bCareRecordService.list(wrapper);
                    for (int j = 0; j < list.size(); j++) {
                        BCareRecord po = list.get(j);

                        String timeStr = DateUtil.format(new Date(list.get(j).getMappedTime()), "yyyy-MM-dd HH:mm:ss");
                        List<Map> mapList = new LinkedList<>();
                        if (mapData.containsKey(timeStr + "@" + po.getUpdatedBy())) {
                            List<Map> dataValue = mapData.get(timeStr + "@" + po.getUpdatedBy());
                            Map map = new LinkedHashMap();
                            map.put("hlcz-itemValue", po.getItemValue());

//                            int contentWidth=CareCommonUtil.getStrWidth(po.getItemValue());
//                            map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));
                            map.put("hlcz-recordId", po.getId());
                            map.put("hlcz-itemCode", po.getItemCode());
                            map.put("operator", po.getUpdatedBy());
                            dataValue.add(map);

                            mapData.put(timeStr + "@" + po.getUpdatedBy(), dataValue);
                        } else {
                            Map map = new LinkedHashMap();
                            map.put("hlcz-itemValue", po.getItemValue());
                            map.put("hlcz-recordId", po.getId());
//                            int contentWidth=CareCommonUtil.getStrWidth(po.getItemValue());
//                            map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));

                            map.put("hlcz-itemCode", po.getItemCode());
                            map.put("operator", po.getUpdatedBy());
                            mapList.add(map);

                            mapData.put(timeStr + "@" + po.getUpdatedBy(), mapList);
                        }
                    }
                    //入量
                } else if (dictValue.equals(ModelItemConstant.MODEL_CRL_IN)) {


                    LambdaQueryWrapper<BIoRecord> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BIoRecord::getHospitalNumber, hospitalNumber);
                    wrapper.eq(BIoRecord::getPatientIdent, patientIdent);
                    wrapper.eq(BIoRecord::getModelCode, "yx-in");
//                    wrapper.eq(BIoRecord::getIsYaoSum, 1);
                    wrapper.eq(BIoRecord::getIsShowCare, CommonConstant.YES_NUMBER);
//                    wrapper.eq(YxHl7YzYaoPlanPO::getIsFromio, 0);
                    wrapper.apply("real_time between '" + startTimeStr + "' and '" + endTimeStr + "'");
                    List<BIoRecord> listIoRecord = bIoRecordService.list(wrapper);


                    List<BIoRecord> listHis = listIoRecord.stream().filter(e -> e.getSource().equals("his")).collect(Collectors.toList());

                    List<BIoRecord> listNoHis = listIoRecord.stream().filter(e -> !e.getSource().equals("his")).collect(Collectors.toList());


                    Map<String, List<BIoRecord>> collectsYaoPlan = listHis.stream().collect(Collectors.groupingBy(e -> fetchGroupKeyIoRecord(e)));

                    for (Map.Entry<String, List<BIoRecord>> entry : collectsYaoPlan.entrySet()) {
                        List<BIoRecord> poList = entry.getValue();

                        List<Map> mapList = new LinkedList<>();
                        String key = entry.getKey();

                        if (mapData.containsKey(key)) {
                            List<Map> dataValue = mapData.get(key);

                            //拿到主药
                            Optional<BIoRecord> havePoListMaster = poList.stream().filter(e -> e.getIsMaster() == 1).findFirst();
                            BIoRecord yxIoRecordPOMaste = new BIoRecord();
                            if (havePoListMaster.isPresent()) {
                                yxIoRecordPOMaste = havePoListMaster.get();
                            }


//                            List<BIoRecord> poListSun = poList.stream().filter(e -> e.getIsMaster() == 0).collect(Collectors.toList());

                            List<BIoRecord> poListSun = bIoRecordMapper.selectIoRecordByGroupId(yxIoRecordPOMaste.getHospitalNumber(), yxIoRecordPOMaste.getPatientIdent(), yxIoRecordPOMaste.getGroupId(), yxIoRecordPOMaste.getPlanTime());

                            StringBuilder name = new StringBuilder();
                            // name.append(yxIoRecordPOMaste.getMedication() + " " + yxIoRecordPOMaste.getDyAmount() + " " + yxIoRecordPOMaste.getDyAmountUnit());
                            Map map = new LinkedHashMap();
//
                            BigDecimal dyAmout = new BigDecimal(0);
                            if (StringUtil.isNotEmpty(yxIoRecordPOMaste.getDyAmount())) {
                                dyAmout = new BigDecimal(yxIoRecordPOMaste.getDyAmount());
                            }


                            //如果剂量和剂量单位不为空 就取 药名,剂量，剂量单位 否则取 药名,规格

                            if (null != yxIoRecordPOMaste && null != yxIoRecordPOMaste.getId()) {
                                if (StringUtil.isNotEmpty(yxIoRecordPOMaste.getDyAmount())) {
                                    map.put("yx-crl-in-yao-name", yxIoRecordPOMaste.getMedication() + " " + dyAmout.stripTrailingZeros().toPlainString() + " " + yxIoRecordPOMaste.getDyAmountUnit());
                                } else {
                                    map.put("yx-crl-in-yao-name", yxIoRecordPOMaste.getMedication() + " " + yxIoRecordPOMaste.getSpec());
                                }

                                map.put("operator", yxIoRecordPOMaste.getUpdatedBy());
                                map.put("yx-crl-in-yao-master-id", yxIoRecordPOMaste.getId());
                                map.put("item-code", yxIoRecordPOMaste.getItemCode());
                                map.put("yx-crl-in-id", yxIoRecordPOMaste.getId());
                                map.put("yx-crl-in-source", yxIoRecordPOMaste.getSource());
                                dataValue.add(map);
                            }


                            for (int j = 0; j < poListSun.size(); j++) {
                                BIoRecord yxIoRecordPOSun = poListSun.get(j);
                                Map mapsun = new LinkedHashMap();
                                if (StringUtil.isNotEmpty(yxIoRecordPOSun.getDyAmount())) {
                                    mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication() + " " + new BigDecimal(yxIoRecordPOSun.getDyAmount()).stripTrailingZeros().toPlainString() + " " + yxIoRecordPOSun.getDyAmountUnit());
                                } else {
                                    mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication() + " " + yxIoRecordPOSun.getSpec());
                                }
                                mapsun.put("item-code", yxIoRecordPOSun.getItemCode());
                                mapsun.put("operator", yxIoRecordPOSun.getUpdatedBy());
                                mapsun.put("yx-crl-in-id", yxIoRecordPOSun.getId());
                                mapsun.put("yx-crl-in-source", yxIoRecordPOSun.getSource());
                                dataValue.add(mapsun);

                            }


                            mapData.put(key, dataValue);
                        } else {


                            //拿到主药
                            Optional<BIoRecord> havePoListMaster = poList.stream().filter(e -> e.getIsMaster() == 1).findFirst();
                            BIoRecord yxIoRecordPOMaste = new BIoRecord();
                            if (havePoListMaster.isPresent()) {
                                yxIoRecordPOMaste = havePoListMaster.get();
                            }


//                            List<BIoRecord> poListSun = poList.stream().filter(e -> e.getIsMaster() == 0).collect(Collectors.toList());
                            List<BIoRecord> poListSun = bIoRecordMapper.selectIoRecordByGroupId(yxIoRecordPOMaste.getHospitalNumber(), yxIoRecordPOMaste.getPatientIdent(), yxIoRecordPOMaste.getGroupId(), yxIoRecordPOMaste.getPlanTime());

                            StringBuilder name = new StringBuilder();
                            // name.append(yxIoRecordPOMaste.getMedication() + " " + yxIoRecordPOMaste.getDyAmount() + " " + yxIoRecordPOMaste.getDyAmountUnit());
                            Map map = new LinkedHashMap();

                            //如果剂量和剂量单位不为空 就取 药名,剂量，剂量单位 否则取 药名,规格

                            BigDecimal dyAmout = new BigDecimal(0);
                            if (StringUtil.isNotEmpty(yxIoRecordPOMaste.getDyAmount())) {
                                dyAmout = new BigDecimal(yxIoRecordPOMaste.getDyAmount());
                            }
                            if (null != yxIoRecordPOMaste && null != yxIoRecordPOMaste.getId()) {
                                if (StringUtil.isNotEmpty(yxIoRecordPOMaste.getDyAmount())) {
                                    map.put("yx-crl-in-yao-name", yxIoRecordPOMaste.getMedication() + " " + dyAmout.stripTrailingZeros().toPlainString() + " " + yxIoRecordPOMaste.getDyAmountUnit());
                                } else {
                                    map.put("yx-crl-in-yao-name", yxIoRecordPOMaste.getMedication() + " " + yxIoRecordPOMaste.getSpec());
                                }
//                                map.put("yx-crl-in-yao-name", yxIoRecordPOMaste.getMedication() + " " + dyAmout.stripTrailingZeros().toPlainString() + " " + yxIoRecordPOMaste.getDyAmountUnit());
                                map.put("operator", yxIoRecordPOMaste.getUpdatedBy());
                                map.put("yx-crl-in-yao-master-id", yxIoRecordPOMaste.getId());
                                map.put("item-code", yxIoRecordPOMaste.getItemCode());
                                map.put("yx-crl-in-id", yxIoRecordPOMaste.getId());
                                map.put("yx-crl-in-source", yxIoRecordPOMaste.getSource());
                                mapList.add(map);
                            }


                            for (int j = 0; j < poListSun.size(); j++) {
                                BIoRecord yxIoRecordPOSun = poListSun.get(j);
                                Map mapsun = new LinkedHashMap();
                                if (StringUtil.isNotEmpty(yxIoRecordPOSun.getDyAmount())) {
                                    mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication() + " " + new BigDecimal(yxIoRecordPOSun.getDyAmount()).stripTrailingZeros().toPlainString() + " " + yxIoRecordPOSun.getDyAmountUnit());
                                } else {
                                    mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication() + " " + yxIoRecordPOSun.getSpec());
                                }
//                                mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication()+new BigDecimal(yxIoRecordPOSun.getDyAmount()).stripTrailingZeros().toPlainString() + " " + yxIoRecordPOSun.getDyAmountUnit());
                                mapsun.put("operator", yxIoRecordPOSun.getUpdatedBy());
                                mapsun.put("item-code", yxIoRecordPOSun.getItemCode());
                                mapsun.put("yx-crl-in-id", yxIoRecordPOSun.getId());
                                mapsun.put("yx-crl-in-source", yxIoRecordPOSun.getSource());
                                mapList.add(mapsun);
                            }

                            mapData.put(key, mapList);
                        }
                    }


                    //非his 数据处理
                    Map<String, List<BIoRecord>> collectsYaoPlanNoHis = listNoHis.stream().collect(Collectors.groupingBy(e -> fetchGroupKeyIoRecord(e)));
                    for (Map.Entry<String, List<BIoRecord>> entry : collectsYaoPlanNoHis.entrySet()) {


                        List<Map> mapList = new LinkedList<>();
                        String key = entry.getKey();
                        List<BIoRecord> listDataOfIoRecord = entry.getValue();


                        if (mapData.containsKey(key)) {
                            List<Map> dataValue = mapData.get(key);

                            for (int j = 0; j < listDataOfIoRecord.size(); j++) {
                                BIoRecord yxIoRecordPOSun = listDataOfIoRecord.get(j);
                                Map mapsun = new LinkedHashMap();
                                if (StringUtil.isNotEmpty(yxIoRecordPOSun.getDyAmount())) {
                                    mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication() + " " + new BigDecimal(yxIoRecordPOSun.getDyAmount()).stripTrailingZeros().toPlainString() + " " + yxIoRecordPOSun.getDyAmountUnit());
                                } else {
                                    mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication() + " " + yxIoRecordPOSun.getSpec());
                                }
                                mapsun.put("item-code", yxIoRecordPOSun.getItemCode());
                                mapsun.put("operator", yxIoRecordPOSun.getUpdatedBy());
                                mapsun.put("yx-crl-in-id", yxIoRecordPOSun.getId());
                                mapsun.put("yx-crl-in-source", yxIoRecordPOSun.getSource());
                                dataValue.add(mapsun);

                            }
                            mapData.put(key, dataValue);
                        } else {


                            for (int j = 0; j < listDataOfIoRecord.size(); j++) {
                                BIoRecord yxIoRecordPOSun = listDataOfIoRecord.get(j);
                                Map mapsun = new LinkedHashMap();
                                if (StringUtil.isNotEmpty(yxIoRecordPOSun.getDyAmount())) {
                                    mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication() + " " + new BigDecimal(yxIoRecordPOSun.getDyAmount()).stripTrailingZeros().toPlainString() + " " + yxIoRecordPOSun.getDyAmountUnit());
                                } else {
                                    mapsun.put("yx-crl-in-yao-name", yxIoRecordPOSun.getMedication() + " " + yxIoRecordPOSun.getSpec());
                                }
                                mapsun.put("item-code", yxIoRecordPOSun.getItemCode());
                                mapsun.put("operator", yxIoRecordPOSun.getUpdatedBy());
                                mapsun.put("yx-crl-in-id", yxIoRecordPOSun.getId());
                                mapsun.put("yx-crl-in-source", yxIoRecordPOSun.getSource());
                                mapList.add(mapsun);

                            }

                            mapData.put(key, mapList);
                        }


                    }
//


                } else if (dictValue.equals(ModelItemConstant.MODEL_CRL_OUT)) {


                    List<IoCodeDetailVO> list = bIoRecordMapper.selectIOOfDetail(ModelItemConstant.MODEL_CRL_OUT, hospitalNumber, minDate, endTimeStr);

//                    Map<LocalDateTime, List<IoCodeDetailVO>> collectsIoTime = list.stream().collect(Collectors.groupingBy(IoCodeDetailVO::getTime));
                    //为了 不同操作者 各种占一行 按照时间和操作人分组
                    Map<String, List<IoCodeDetailVO>> collectsIoTime = list.stream().collect(Collectors.groupingBy(e -> fetchGroupKeyCrl(e)));

                    for (Map.Entry<String, List<IoCodeDetailVO>> entry : collectsIoTime.entrySet()) {
                        List<IoCodeDetailVO> poList = entry.getValue();

                        String key = entry.getKey();

                        if (mapData.containsKey(key)) {
                            List<Map> dataValue = mapData.get(key);

                            for (int j = 0; j < poList.size(); j++) {
                                IoCodeDetailVO vo = poList.get(j);

                                Map map = new LinkedHashMap();
                                map.put("yx-crl-out-name", vo.getItemName());
                                map.put("yx-crl-out-value", vo.getIoValue() + "ml");
                                map.put("yx-crl-out-id", vo.getId());
//                                int contentWidth=CareCommonUtil.getStrWidth(vo.getIoValue() + "ml");
//                                map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));
                                map.put("operator", vo.getUpdatedBy());
                                map.put("item-code", vo.getItemCode());
                                map.put("yx-crl-out-source", vo.getSource());
                                dataValue.add(map);
                            }
                            mapData.put(key, dataValue);
                        } else {
                            List<Map> mapList = new LinkedList<>();

                            for (int j = 0; j < poList.size(); j++) {
                                IoCodeDetailVO vo = poList.get(j);
                                Map map = new LinkedHashMap();
                                map.put("yx-crl-out-name", vo.getItemName());
                                map.put("yx-crl-out-value", vo.getIoValue() + "ml");
                                map.put("yx-crl-out-id", vo.getId());
//                                int contentWidth=CareCommonUtil.getStrWidth(vo.getIoValue() + "ml");
//                                map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));
                                map.put("operator", vo.getUpdatedBy());
                                map.put("item-code", vo.getItemCode());
                                map.put("yx-crl-out-source", vo.getSource());
                                mapList.add(map);
                            }
                            mapData.put(key, mapList);
                        }

                    }

                } else if (dictValue.equals(ModelItemConstant.MODEL_VTE_DD)) {
                    //类型 ：1 vte 、2 肌酐、3 APACHEll、4 病人跌倒/坠床高危评估表（成人）、5 压力性损伤记录  、6  braden评分
                    LambdaQueryWrapper<BCarePgVte> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BCarePgVte::getHospitalNumber, hospitalNumber);
                    wrapper.eq(BCarePgVte::getType, 4);
                    wrapper.eq(BCarePgVte::getIsDeleted, 0);
                    wrapper.apply("pf_time between '" + minDate + "' and '" + endTimeStr + "'");


                    List<BCarePgVte> list = bCarePgVteService.list(wrapper);
                    Map<String, List<BCarePgVte>> collectsIoTime = list.stream().collect(Collectors.groupingBy(e -> fetchGroupKeyVte(e)));

                    for (Map.Entry<String, List<BCarePgVte>> entry : collectsIoTime.entrySet()) {
                        List<BCarePgVte> poList = entry.getValue();

                        String key = entry.getKey();

                        if (mapData.containsKey(key)) {
                            List<Map> dataValue = mapData.get(key);

                            for (int j = 0; j < poList.size(); j++) {
                                BCarePgVte vo = poList.get(j);

                                Map map = new LinkedHashMap();
                                map.put("vte-dd-result", vo.getResult());
                                map.put("vte-dd-id", vo.getId());
//                                int contentWidth=CareCommonUtil.getStrWidth(vo.getResult());
//                                map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));
//                                map.put("str-width",  contentWidth);
                                map.put("pf-type", vo.getPfType());
                                map.put("operator", vo.getUpdatedBy());

                                dataValue.add(map);
                            }
                            mapData.put(key, dataValue);
                        } else {
                            List<Map> mapList = new LinkedList<>();

                            for (int j = 0; j < poList.size(); j++) {
                                BCarePgVte vo = poList.get(j);
                                Map map = new LinkedHashMap();
                                map.put("vte-dd-result", vo.getResult());
                                map.put("vte-dd-id", vo.getId());
//                                int contentWidth=CareCommonUtil.getStrWidth(vo.getResult());
//                                map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));
//                                map.put("str-width",  contentWidth);
                                map.put("pf-type", vo.getPfType());
                                map.put("operator", vo.getUpdatedBy());

                                mapList.add(map);
                            }
                            mapData.put(key, mapList);
                        }

                    }


                } else if (dictValue.equals(ModelItemConstant.MODEL_VTE_BRADE)) {
                    //类型 ：1 vte 、2 肌酐、3 APACHEll、4 病人跌倒/坠床高危评估表（成人）、5 压力性损伤记录  、6  braden评分
                    LambdaQueryWrapper<BCarePgVte> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(BCarePgVte::getHospitalNumber, hospitalNumber);
                    wrapper.eq(BCarePgVte::getType, 6);
                    wrapper.eq(BCarePgVte::getIsDeleted, 0);
                    wrapper.apply("pf_time between '" + minDate + "' and '" + endTimeStr + "'");


                    List<BCarePgVte> list = bCarePgVteService.list(wrapper);
                    Map<String, List<BCarePgVte>> collectsIoTime = list.stream().collect(Collectors.groupingBy(e -> fetchGroupKeyVte(e)));

                    for (Map.Entry<String, List<BCarePgVte>> entry : collectsIoTime.entrySet()) {
                        List<BCarePgVte> poList = entry.getValue();

                        String key = entry.getKey();

                        if (mapData.containsKey(key)) {
                            List<Map> dataValue = mapData.get(key);

                            for (int j = 0; j < poList.size(); j++) {
                                BCarePgVte vo = poList.get(j);

                                Map map = new LinkedHashMap();
                                map.put("vte-brade-result", vo.getResult());
                                map.put("vte-brade-id", vo.getId());
//                                int contentWidth=CareCommonUtil.getStrWidth(vo.getResult());
//                                map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));
                                map.put("operator", vo.getUpdatedBy());

                                dataValue.add(map);
                            }
                            mapData.put(key, dataValue);
                        } else {
                            List<Map> mapList = new LinkedList<>();

                            for (int j = 0; j < poList.size(); j++) {
                                BCarePgVte vo = poList.get(j);
                                Map map = new LinkedHashMap();
                                map.put("vte-brade-result", vo.getResult());
                                map.put("vte-brade-id", vo.getId());
//                                int contentWidth=CareCommonUtil.getStrWidth(vo.getResult());
//                                map.put("str-multiple",  CareCommonUtil.devideResult(new BigDecimal(contentWidth),new BigDecimal(jishu),2));
                                map.put("operator", vo.getUpdatedBy());

                                mapList.add(map);
                            }
                            mapData.put(key, mapList);
                        }

                    }


                }
            }
        }


        //每一行必须要有某个模块某个选项有一个值的逻辑，去掉整条数据都是null的数据
        mapData.forEach((k, v) -> {
            // System.out.println(k + " : " + v);
            List<Map> rowData = v;
            AtomicBoolean haveDelete = new AtomicBoolean(false);
            for (int i = 0; i < rowData.size(); i++) {
                Map mapDataNode = rowData.get(i);
                mapDataNode.forEach((rowK, rowV) -> {
                    if (rowK.equals("hljl-careContent")) {
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("pgpf-showValue")) {
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("gcx-propValue")) {
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("crl-ioValue")) {
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("hlcz-itemValue")) {
                        //说明至少有一个选项有值
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("yx-crl-in-value")) {
                        //说明至少有一个选项有值
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("yx-crl-in-yao-name")) {
                        //说明至少有一个选项有值
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("yx-crl-out-value")) {
                        //说明至少有一个选项有值
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("vte-dd-result")) {
                        //说明至少有一个选项有值
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    } else if (rowK.equals("vte-brade-result")) {
                        //说明至少有一个选项有值
                        String content = (String) rowV;
                        if (StringUtil.isNotEmpty(content)) {
                            //说明至少有一个选项有值
                            haveDelete.set(true);
                        }
                    }


                });
            }


            //如果是false 代表整个map行的选项数值都是null
            if (haveDelete.compareAndSet(false, true)) {
                mapData.remove(k);
            }
        });
        //按照key里额时间值 做升序排序
        // 转换为list

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        List<Date> haveDataDate = new LinkedList<>();
        List<String> haveDataDataString = new LinkedList<>();
        mapData.forEach((k, v) -> {

            String dateStr = k;
            if (StringUtil.isNotEmpty(dateStr)) {
                if (dateStr.contains("@")) {
                    int i = dateStr.indexOf("@");//首先获取字符的位置
                    String newdateStr = dateStr.substring(0, i);

                    if (StringUtil.isNotEmpty(newdateStr) && !newdateStr.equals("null")) {
                        Date date = DateUtil.parse(newdateStr);
                        haveDataDate.add(date);
                        haveDataDataString.add(DateUtil.formatDate(date));
                    }
                } else {
                    Date date = DateUtil.parse(dateStr);
                    haveDataDate.add(date);
                    haveDataDataString.add(DateUtil.formatDate(date));
                }
            }


            //得到日期yyyy-MM-dd
//            dateStr = dateStr.substring(0, 10);

            // mapForDate.put(dateStr, 1);
        });
        Date dateRk = DateUtil.parseDateTime(startTimeStr);
        //结束时间 date类型
        Date cyTime = new Date(endTime);

        //根据开始时间和结束时间返回时间段内的时间集合
        List<String> listAllDates = YDateUtils.getDatesBetweenTwoDate(dateRk, cyTime);

        //日期字符去重
        List<String> uniqueListHaveData = haveDataDataString.stream().distinct().collect(Collectors.toList());
        //去掉有数据的那些日期
        List<String> dateAfterRemove = CareCommonUtil.listRemove(listAllDates, uniqueListHaveData);

        //删除已经统计过的第一天日期
        dateAfterRemove.removeIf(s -> s.contains(DateUtil.formatDate(dateRk)));
        //排除已有统计中第一天的日期
        uniqueListHaveData.removeIf(s -> s.contains(DateUtil.formatDate(dateRk)));

        //先过滤出院那天的时间  单独统计
        Date finalCyTime = cyTime;
        dateAfterRemove.removeIf(s -> s.contains(DateUtil.formatDate(finalCyTime)));

        //先过滤出院那天的时间  单独统计
        uniqueListHaveData.removeIf(s -> s.contains(DateUtil.formatDate(finalCyTime)));

        Calendar cRk = Calendar.getInstance();
        cRk.setTime(dateRk);
        cRk.add(Calendar.DATE, 1);
        //入科时间加一天
        Date dateRkAfter = cRk.getTime();
        String nextDayRK = DateUtil.formatDate(dateRkAfter);

        Calendar cRkFront = Calendar.getInstance();
        cRk.setTime(dateRk);
        cRk.add(Calendar.DATE, -1);
        //入科时间加一天
        Date dateRkFront = cRkFront.getTime();
        String frontDayRK = DateUtil.formatDate(dateRkFront);

        //用来取采集人名称的
        Map<String, List<BObsvRecord>> collectsObsvMapForCaijiren = listObsvResult.stream().filter(e -> StringUtil.isNotEmpty(e.getCaijiren())).collect(Collectors.groupingBy(e -> fetchGroupKeyObsv(e)));


        //第一条记录 ################################################################################################>>
        Date dateAStart = DateUtil.parseDateTime(DateUtil.formatDate(dateRk) + " 07:00:01");
        Date dateAEnd = DateUtil.parseDateTime(DateUtil.formatDate(dateRk) + " 16:00:00");

        Date datePStart = DateUtil.parseDateTime(DateUtil.formatDate(dateRk) + " 16:00:01");
        Date datePEnd = DateUtil.parseDateTime(DateUtil.formatDate(dateRkAfter) + " 00:00:00");

        Date dateNStart = DateUtil.parseDateTime(DateUtil.formatDate(dateRkAfter) + " 00:00:01");
        Date dateNEnd = DateUtil.parseDateTime(DateUtil.formatDate(dateRkAfter) + " 07:00:00");


        //是否属于A班
        Boolean isA = YDateUtils.belongCalendar(dateRk, dateAStart, dateAEnd);

        Boolean isP = YDateUtils.belongCalendar(dateRk, datePStart, datePEnd);

        Boolean isN = YDateUtils.belongCalendar(dateRk, dateNStart, dateNEnd);


        //三个班次 总入量 总出量统计
        List<IoModelVO> listModelCodeAllOfRkFirst = bIoRecordMapper.selectSumOfModelAll(hospitalNumber, DateUtil.formatDate(dateRk) + " 07:00:01", DateUtil.formatDate(dateRk) + " 16:00:00",
                DateUtil.formatDate(dateRk) + " 16:00:01", nextDayRK + " 00:00:00",
                DateUtil.formatDate(dateRk) + " 07:00:01", nextDayRK + " 07:00:00", CommonConstant.YES_NUMBER);
//                DateUtil.formatDate(dateRkFront) + " 00:00:01", dateRk + " 07:00:00");

        List<IoDetailVO> ioDetailVOListAllRkFirst = bIoRecordMapper.selectSumOfDetailAll(hospitalNumber, DateUtil.formatDate(dateRk) + " 07:00:01", DateUtil.formatDate(dateRk) + " 16:00:00",
                DateUtil.formatDate(dateRk) + " 16:00:01", nextDayRK + " 00:00:00",
                DateUtil.formatDate(dateRk) + " 07:00:01", nextDayRK + " 07:00:00", CommonConstant.YES_NUMBER);
//                DateUtil.formatDate(dateRkFront) + " 07:00:01", dateRk + " 07:00:00");


        //入科当天首次统计处理
        //如果入科时间是A班的
        if (isA) {
            Map mapInit = new HashMap();

            //总入量
            BigDecimal inSumValue = new BigDecimal(0);
            BigDecimal outSumValue = new BigDecimal(0);

            List<IoModelVO> listModelCodeAOfRK = listModelCodeAllOfRkFirst.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());

            IoModelVO firstIn = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstIn) {
                inSumValue = firstIn.getSumValue();
            }

            IoModelVO firstOut = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOut) {
                outSumValue = firstOut.getSumValue();
            }

            StringBuilder stringBuilderInDetail;
            StringBuilder stringBuilderOutDetail;


            List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllRkFirst.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());
//            stringBuilderInDetail = getInContent(ioDetailVOListA);
            stringBuilderOutDetail = getOutContent(ioDetailVOListA);

            //平衡量
//            BigDecimal phl = inSumValue.subtract(outSumValue);


            mapInit.put("统计A班", " (" + YDateUtils.getDatePoor(dateAEnd, dateRk) + ") 总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

            List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get((DateUtil.formatDate(dateRk) + " 16:00:00") + "@" + patientIdent);
            if (CollectionUtils.isNotEmpty(listObsv)) {
                Optional<BObsvRecord> result = listObsv.stream().findFirst();
                if (result.isPresent()) {
                    String user = result.get().getCaijiren();
                    if (StrUtil.isNotEmpty(user)) {
                        mapInit.put("operator", user);
                    }
                }
            }

            List<Map> mapNode = new ArrayList<>();
            mapNode.add(mapInit);
            mapData.put(DateUtil.formatDate(dateRk) + " 16:00:01#", mapNode);

            Long timeP = DateUtil.parseDateTime(DateUtil.formatDate(dateRk) + " 16:00:01").getTime();
            //如果结束时间超过了这个班次的开始时间那么就显示这个班次的时间
            if (endTime > timeP) {
                //加入P班的统计
                List<Map> listMapNodeP = getPOfSum(listModelCodeAllOfRkFirst, ioDetailVOListAllRkFirst, dateNEnd, dateRk, patientIdent, collectsObsvMapForCaijiren);
                mapData.put(DateUtil.formatDate(dateRkAfter) + " 00:00:01#", listMapNodeP);
            }

            Long timeN = DateUtil.parseDateTime(nextDayRK + " 00:00:01").getTime();
            if (endTime > timeN) {
                //加入N班的统计
                List<Map> listMapNodeN = getNOfSum(listModelCodeAllOfRkFirst, ioDetailVOListAllRkFirst, dateNEnd, dateRk, patientIdent, collectsObsvMapForCaijiren);
                mapData.put(DateUtil.formatDate(dateRkAfter) + " 07:00:01#", listMapNodeN);
            }


            //如果入科时间是P班的
        } else if (isP) {
            Map mapInit = new HashMap();

            //总入量
            BigDecimal inSumValue = new BigDecimal(0);
            BigDecimal outSumValue = new BigDecimal(0);

            List<IoModelVO> listModelCodeAOfRK = listModelCodeAllOfRkFirst.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

            IoModelVO firstIn = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstIn) {
                inSumValue = firstIn.getSumValue();
            }

            IoModelVO firstOut = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOut) {
                outSumValue = firstOut.getSumValue();
            }

            StringBuilder stringBuilderInDetail;
            StringBuilder stringBuilderOutDetail;


            List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllRkFirst.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());
//            stringBuilderInDetail = getInContent(ioDetailVOListA);
            stringBuilderOutDetail = getOutContent(ioDetailVOListA);

            //平衡量
//            BigDecimal phl = inSumValue.subtract(outSumValue);

            mapInit.put("统计P班", " (" + YDateUtils.getDatePoor(datePEnd, dateRk) + ") 总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + ";总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

            List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get((DateUtil.formatDate(dateRkAfter) + " 00:00:00") + "@" + patientIdent);
            if (CollectionUtils.isNotEmpty(listObsv)) {
                Optional<BObsvRecord> result = listObsv.stream().findFirst();
                if (result.isPresent()) {
                    String user = result.get().getCaijiren();
                    if (StrUtil.isNotEmpty(user)) {
                        mapInit.put("operator", user);
                    }
                }
            }
            List<Map> mapNode = new ArrayList<>();
            mapNode.add(mapInit);

            mapData.put(DateUtil.formatDate(dateRkAfter) + " 00:00:01#", mapNode);


            Long timeN = DateUtil.parseDateTime(nextDayRK + " 00:00:01").getTime();
            if (endTime > timeN) {
                //添加N班的统计
                List<Map> listMapNode = getNOfSum(listModelCodeAllOfRkFirst, ioDetailVOListAllRkFirst, dateNEnd, dateRk, patientIdent, collectsObsvMapForCaijiren);
                mapData.put(DateUtil.formatDate(dateRkAfter) + " 07:00:01#", listMapNode);
            }

        } else if (isN) {
            Map mapInit = new HashMap();

            //总入量
            BigDecimal inSumValue = new BigDecimal(0);
            BigDecimal outSumValue = new BigDecimal(0);

            List<IoModelVO> listModelCodeAOfRK = listModelCodeAllOfRkFirst.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());

            IoModelVO firstIn = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstIn) {
                inSumValue = firstIn.getSumValue();
            }

            IoModelVO firstOut = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOut) {
                outSumValue = firstOut.getSumValue();
            }

            StringBuilder stringBuilderInDetail;
            StringBuilder stringBuilderOutDetail;


            List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllRkFirst.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());
//            stringBuilderInDetail = getInContent(ioDetailVOListA);
            stringBuilderOutDetail = getOutContent(ioDetailVOListA);

            //平衡量
            BigDecimal phl = inSumValue.subtract(outSumValue);


            mapInit.put("统计N班", " (" + YDateUtils.getDatePoor(dateNEnd, dateRk) + ")  总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

            List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get((DateUtil.formatDate(dateRk) + " 07:00:00") + "@" + patientIdent);
            if (CollectionUtils.isNotEmpty(listObsv)) {
                Optional<BObsvRecord> result = listObsv.stream().findFirst();
                if (result.isPresent()) {
                    String user = result.get().getCaijiren();
                    if (StrUtil.isNotEmpty(user)) {
                        mapInit.put("operator", user);
                    }
                }
            }
            List<Map> mapNode = new ArrayList<>();
            mapNode.add(mapInit);

            mapData.put(DateUtil.formatDate(dateRk) + " 07:00:01#", mapNode);
        }


        //第一条记录结束 <<################################################################################################


        //出院时间/结束时间  单独处理 ==================================>

        String cyTimeDateStr = DateUtil.formatDate(cyTime);

        Calendar cCY = Calendar.getInstance();
        cCY.setTime(cyTime);
        cCY.add(Calendar.DATE, 1);
        //出院时间加一天
        Date dateCyAfter = cCY.getTime();
        String nextDayCY = DateUtil.formatDate(dateCyAfter);

        Calendar cCYFront = Calendar.getInstance();
        cCY.setTime(cyTime);
        cCY.add(Calendar.DATE, -1);
        //出院时间加一天
        Date dateCyFront = cCYFront.getTime();
        String frontDayCY = DateUtil.formatDate(dateCyFront);

        //三个班次 总入量 总出量统计
        List<IoModelVO> listModelCodeAllOfCY = bIoRecordMapper.selectSumOfModelAll(hospitalNumber, cyTimeDateStr + " 07:00:01", cyTimeDateStr + " 16:00:00",
                cyTimeDateStr + " 16:00:01", nextDayCY + " 00:00:00",
                cyTimeDateStr + " 07:00:01", nextDayCY + " 07:00:00", CommonConstant.YES_NUMBER);
//                frontDayCY + " 07:00:01", cyTimeDateStr + " 07:00:00");
        //出入量具体明细项目 统计
        List<IoDetailVO> ioDetailVOListAllCY = bIoRecordMapper.selectSumOfDetailAll(hospitalNumber, cyTimeDateStr + " 07:00:01", cyTimeDateStr + " 16:00:00",
                cyTimeDateStr + " 16:00:01", nextDayCY + " 00:00:00",
                cyTimeDateStr + " 07:00:01", nextDayCY + " 07:00:00", CommonConstant.YES_NUMBER);
//                frontDayCY + " 07:00:01", cyTimeDateStr + " 07:00:00");

        Date dateAStartOfCY = DateUtil.parseDateTime(DateUtil.formatDate(cyTime) + " 07:00:01");
        Date dateAEndOfCY = DateUtil.parseDateTime(DateUtil.formatDate(cyTime) + " 16:00:00");

        Date datePStartOfCY = DateUtil.parseDateTime(DateUtil.formatDate(cyTime) + " 16:00:01");
        Date datePEndOfCY = DateUtil.parseDateTime(DateUtil.formatDate(dateCyAfter) + " 00:00:00");

        Date dateNStartOfCY = DateUtil.parseDateTime(DateUtil.formatDate(dateCyAfter) + " 00:00:01");
        Date dateNEndOfCY = DateUtil.parseDateTime(DateUtil.formatDate(dateCyAfter) + " 07:00:00");


        //是否属于A班
        Boolean isACy = YDateUtils.belongCalendar(cyTime, dateAStartOfCY, dateAEndOfCY);

        Boolean isPCy = YDateUtils.belongCalendar(cyTime, datePStartOfCY, datePEndOfCY);

        Boolean isNCy = YDateUtils.belongCalendar(cyTime, dateNStartOfCY, dateNEndOfCY);


        String resultEndTimeStr = "";
        if (isACy) {
            Map mapCy = new HashMap();

            //总入量
            BigDecimal inSumValue = new BigDecimal(0);
            BigDecimal outSumValue = new BigDecimal(0);

            List<IoModelVO> listModelCodeAOfCY = listModelCodeAllOfCY.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());

            IoModelVO firstIn = listModelCodeAOfCY.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstIn) {
                inSumValue = firstIn.getSumValue();
            }

            IoModelVO firstOut = listModelCodeAOfCY.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOut) {
                outSumValue = firstOut.getSumValue();
            }

            StringBuilder stringBuilderInDetail;
            StringBuilder stringBuilderOutDetail;


            List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllCY.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());
//            stringBuilderInDetail = getInContent(ioDetailVOListA);
            stringBuilderOutDetail = getOutContent(ioDetailVOListA);

            //平衡量
//            BigDecimal phl = inSumValue.subtract(outSumValue);
            int hour = YDateUtils.getCurrentHour(cyTime);
            int minute = YDateUtils.getCurrentMinute(cyTime);
            String minuteStr = minute + "";

            String times = (hour - 7) + "小时" + minute + "分钟";
            if (hour == 9) {

            }

            String dateStr = DateUtil.formatDate(cyTime);

            String cyDateStr = DateUtil.formatDate(cyTime);

            mapCy.put("统计A班", " (" + times + ") 总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

            List<Map> mapNode = new ArrayList<>();

            String caijiren = bObsvRecordMapper.selectCaijirenByTime(patientIdent, YDateUtils.stringToDate(cyDateStr + " 07:00:01", YDateUtils.DATE_TIME_PATTERN).getTime(), YDateUtils.stringToDate(cyDateStr + " 16:00:00", YDateUtils.DATE_TIME_PATTERN).getTime());
            mapCy.put("operator", caijiren);
            mapNode.add(mapCy);


            String hourAndMinute = "";
            if (minuteStr.length() == 1) {
                hourAndMinute = " " + hour + ":0" + minute + "#";
            } else if (minuteStr.length() == 2) {
                hourAndMinute = " " + hour + ":" + minute + "#";
            }


            resultEndTimeStr = dateStr + hourAndMinute;


            mapData.put(dateStr + hourAndMinute, mapNode);


            //如果入科时间是P班的
        } else if (isPCy) {


            //加入A班的统计
            String cydateStr = DateUtil.formatDate(cyTime);

            Date dateV = DateUtil.parseDate(cydateStr);
            Calendar cANext = Calendar.getInstance();
            cANext.setTime(dateV);
            cANext.add(Calendar.DATE, 1);
            Date dateVAfter = cANext.getTime();
            String nextDay = DateUtil.formatDate(dateVAfter);
            List<Map> mapNodeA = getListSumOfA(cydateStr, hospitalNumber, nextDay, patientIdent, collectsObsvMapForCaijiren);
            mapData.put(cydateStr + " 16:00:01#", mapNodeA);


            Map mapCy = new HashMap();

            //总入量
            BigDecimal inSumValue = new BigDecimal(0);
            BigDecimal outSumValue = new BigDecimal(0);

            List<IoModelVO> listModelCodeAOfCY = listModelCodeAllOfCY.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

            IoModelVO firstIn = listModelCodeAOfCY.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstIn) {
                inSumValue = firstIn.getSumValue();
            }

            IoModelVO firstOut = listModelCodeAOfCY.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOut) {
                outSumValue = firstOut.getSumValue();
            }

            StringBuilder stringBuilderInDetail;
            StringBuilder stringBuilderOutDetail;


            List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllCY.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());
            stringBuilderInDetail = getInContent(ioDetailVOListA);
            stringBuilderOutDetail = getOutContent(ioDetailVOListA);

            //平衡量
            BigDecimal phl = inSumValue.subtract(outSumValue);

            int hour = YDateUtils.getCurrentHour(cyTime);
            int minute = YDateUtils.getCurrentMinute(cyTime);
            String times = (hour - 16) + "小时" + minute + "分钟";

            //mapCy.put("统计P班", "(8小时) " + times + " 总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;"  + ";总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);
            mapCy.put("统计P班", " (" + times + ") 总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + ";总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);
            List<Map> mapNode = new ArrayList<>();

            String cyDateStr = DateUtil.formatDate(cyTime);

//            List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get(cyDateStr+ " 00:00:00" + "@" + patientIdent);
//            if (CollectionUtils.isNotEmpty(listObsv)) {
//                Optional<BObsvRecord> result = listObsv.stream().findFirst();
//                if(result.isPresent()){
//                    String user = result.get().getCaijiren();
//                    if (StrUtil.isNotEmpty(user)) {
//                        mapCy.put("operator",user);
//                    }
//                }
//            }

            Calendar c = Calendar.getInstance();
            c.setTime(cyTime);
            c.add(Calendar.DATE, 1);
            Date cyTimeAfter = c.getTime();
            // String nextDay = DateUtil.formatDate(cyTimeAfter);
            //P班显示时间+1天
            String dateStrP = DateUtil.formatDate(cyTimeAfter);

            String caijiren = bObsvRecordMapper.selectCaijirenByTime(patientIdent, YDateUtils.stringToDate(cyDateStr + " 16:00:01", YDateUtils.DATE_TIME_PATTERN).getTime(), YDateUtils.stringToDate(dateStrP + " 00:00:00", YDateUtils.DATE_TIME_PATTERN).getTime());
            mapCy.put("operator", caijiren);

            mapNode.add(mapCy);


//            String hourAndMinute = " " + hour + ":" + minute + "#";
            String minuteStr = minute + "";
            String hourAndMinute = "";
            if (minuteStr.length() == 1) {
                hourAndMinute = " " + hour + ":0" + minute + "#";
            } else if (minuteStr.length() == 2) {
                hourAndMinute = " " + hour + ":" + minute + "#";
            }
            resultEndTimeStr = dateStrP + hourAndMinute;
            mapData.put(dateStrP + hourAndMinute, mapNode);


            //如果入科时间是N班的
        } else if (isNCy) {

            //加入N班的统计
            String cydateStr = DateUtil.formatDate(cyTime);

            Date dateV = DateUtil.parseDate(cydateStr);
            Calendar cANext = Calendar.getInstance();
            cANext.setTime(dateV);
            cANext.add(Calendar.DATE, 1);
            Date dateVAfter = cANext.getTime();
            String nextDay = DateUtil.formatDate(dateVAfter);

            Calendar cAFront = Calendar.getInstance();
            cAFront.setTime(dateV);
            cAFront.add(Calendar.DATE, -1);
            Date dateVFront = cAFront.getTime();
            String frontDay = DateUtil.formatDate(dateVFront);


            List<Map> mapNodeA = getListSumOfA(cydateStr, hospitalNumber, nextDay, patientIdent, collectsObsvMapForCaijiren);
            mapData.put(cydateStr + " 16:00:01#", mapNodeA);


            //加入P班的统计
            List<Map> mapNodeP = getListSumOfP(nextDay, hospitalNumber, nextDay, patientIdent, collectsObsvMapForCaijiren);
            mapData.put(cydateStr + " 00:00:01#", mapNodeP);


            //开始统计出院当天的N班
            Map mapCy = new HashMap();

            //总入量
            BigDecimal inSumValue = new BigDecimal(0);
            BigDecimal outSumValue = new BigDecimal(0);

            List<IoModelVO> listModelCodeAOfCY = listModelCodeAllOfCY.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());

            IoModelVO firstIn = listModelCodeAOfCY.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstIn) {
                inSumValue = firstIn.getSumValue();
            }

            IoModelVO firstOut = listModelCodeAOfCY.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOut) {
                outSumValue = firstOut.getSumValue();
            }

            StringBuilder stringBuilderInDetail;
            StringBuilder stringBuilderOutDetail;


            List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllCY.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());
//            stringBuilderInDetail = getInContent(ioDetailVOListA);
            stringBuilderOutDetail = getOutContent(ioDetailVOListA);

            //平衡量
//            BigDecimal phl = inSumValue.subtract(outSumValue);

            mapCy.put("统计N班", " （" + YDateUtils.getCurrentHourAndMinute(cyTime, 17) + ")  总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

            List<Map> mapNode = new ArrayList<>();

            Calendar c = Calendar.getInstance();
            c.setTime(cyTime);
            c.add(Calendar.DATE, 1);
            Date cyTimeAfter = c.getTime();
            //String nextDay = DateUtil.formatDate(cyTimeAfter);
            //N班显示时间+1天  新需求改成 显示结束的实际时间

            int hour = YDateUtils.getCurrentHour(cyTime);
            int minute = YDateUtils.getCurrentMinute(cyTime);

            String dateStr = DateUtil.formatDate(cyTimeAfter);

            String caijiren = bObsvRecordMapper.selectCaijirenByTime(patientIdent, YDateUtils.stringToDate(dateStr + " 00:00:01", YDateUtils.DATE_TIME_PATTERN).getTime(), YDateUtils.stringToDate(dateStr + " 07:00:00", YDateUtils.DATE_TIME_PATTERN).getTime());
            mapCy.put("operator", caijiren);

            mapNode.add(mapCy);


            String minuteStr = minute + "";
            String hourAndMinute = "";
            if (minuteStr.length() == 1) {
                hourAndMinute = " " + hour + ":0" + minute + "#";
            } else if (minuteStr.length() == 2) {
                hourAndMinute = " " + hour + ":" + minute + "#";
            }
            resultEndTimeStr = dateStr + hourAndMinute;
            mapData.put(dateStr + hourAndMinute, mapNode);


        } else {
            //如果不在这三个班次内 有可能是前一天的N班


            //加入N班的统计
            String cydateStr = DateUtil.formatDate(cyTime);

            Date dateV = DateUtil.parseDate(cydateStr);
//            Calendar cANext = Calendar.getInstance();
//            cANext.setTime(dateV);
//            cANext.add(Calendar.DATE, 1);
//            Date dateVAfter = cANext.getTime();
//            String nextDay = DateUtil.formatDate(dateVAfter);

            Calendar cAFront = Calendar.getInstance();
            cAFront.setTime(dateV);
            cAFront.add(Calendar.DATE, -1);
            Date dateVFront = cAFront.getTime();
            String frontDay = DateUtil.formatDate(dateVFront);

            List<IoModelVO> listModelCodeAllOfCYFront = bIoRecordMapper.selectSumOfModelAll(hospitalNumber, frontDay + " 07:00:01", cyTimeDateStr + " 16:00:00",
                    frontDay + " 16:00:01", nextDayCY + " 00:00:00",
                    cyTimeDateStr + " 07:00:01", nextDayCY + " 07:00:00", CommonConstant.YES_NUMBER);
//                frontDayCY + " 07:00:01", cyTimeDateStr + " 07:00:00");
            //出入量具体明细项目 统计
            List<IoDetailVO> ioDetailVOListAllCYFront = bIoRecordMapper.selectSumOfDetailAll(hospitalNumber, cyTimeDateStr + " 07:00:01", cyTimeDateStr + " 16:00:00",
                    cyTimeDateStr + " 16:00:01", nextDayCY + " 00:00:00",
                    cyTimeDateStr + " 07:00:01", nextDayCY + " 07:00:00", CommonConstant.YES_NUMBER);


            List<Map> mapNodeA = getListSumOfA(frontDay, hospitalNumber, cydateStr, patientIdent, collectsObsvMapForCaijiren);
            mapData.put(frontDay + " 16:00:01#", mapNodeA);


            //加入P班的统计
            List<Map> mapNodeP = getListSumOfP(frontDay, hospitalNumber, cydateStr, patientIdent, collectsObsvMapForCaijiren);
            mapData.put(cydateStr + " 00:00:01#", mapNodeP);


            //开始统计出院当天的N班
            Map mapCy = new HashMap();

            //总入量
            BigDecimal inSumValue = new BigDecimal(0);
            BigDecimal outSumValue = new BigDecimal(0);

            List<IoModelVO> listModelCodeAOfCY = listModelCodeAllOfCYFront.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());

            IoModelVO firstIn = listModelCodeAOfCY.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstIn) {
                inSumValue = firstIn.getSumValue();
            }

            IoModelVO firstOut = listModelCodeAOfCY.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOut) {
                outSumValue = firstOut.getSumValue();
            }

            StringBuilder stringBuilderInDetail;
            StringBuilder stringBuilderOutDetail;


            List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllCYFront.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());
//            stringBuilderInDetail = getInContent(ioDetailVOListA);
            stringBuilderOutDetail = getOutContent(ioDetailVOListA);

            //平衡量
//            BigDecimal phl = inSumValue.subtract(outSumValue);

            mapCy.put("统计N班", " （" + YDateUtils.getCurrentHourAndMinute(cyTime, 17) + ")  总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

            List<Map> mapNode = new ArrayList<>();

            Calendar c = Calendar.getInstance();
            c.setTime(cyTime);
            c.add(Calendar.DATE, 1);
            Date cyTimeAfter = c.getTime();
            //String nextDay = DateUtil.formatDate(cyTimeAfter);
            //N班显示时间+1天  新需求改成 显示结束的实际时间

            int hour = YDateUtils.getCurrentHour(cyTime);
            int minute = YDateUtils.getCurrentMinute(cyTime);

            String dateStr = DateUtil.formatDate(cyTimeAfter);

            String caijiren = bObsvRecordMapper.selectCaijirenByTime(patientIdent, YDateUtils.stringToDate(dateStr + " 00:00:01", YDateUtils.DATE_TIME_PATTERN).getTime(), YDateUtils.stringToDate(dateStr + " 07:00:00", YDateUtils.DATE_TIME_PATTERN).getTime());
            mapCy.put("operator", caijiren);

            mapNode.add(mapCy);


            String minuteStr = "";
            String hourStr = "";
            String hourAndMinute = "";

            if (hourStr.length() > 1) {
                hourStr = hour + "";
            } else {
                hourStr = "0" + hour;
            }
            if (minuteStr.length() > 1) {
                minuteStr = minute + "";
            } else {
                minuteStr = "0" + minute;
            }
            hourAndMinute = " " + hourStr + ":" + minuteStr + ":01" + "#";
//            if (minuteStr.length() == 1) {
//                if(hourStr.length()==1){
//                    hourAndMinute = " " + hour + ":0" + minute + "#";
//                }
//
//            } else if (minuteStr.length() == 2) {
//                hourAndMinute = " " + hour + ":" + minute + "#";
//            }
            resultEndTimeStr = cyTimeDateStr + hourAndMinute;
            if (null != mapData.get(cyTimeDateStr + hourAndMinute)) {
                //说明入院处理那边已经有这个班次了
            } else {
                mapData.put(cyTimeDateStr + hourAndMinute, mapNode);
            }


        }


        //出院单独处理 结束 <====================================

        ZoneId zoneId = ZoneId.systemDefault();
        //循环 没有数据的日期 ================================================================================================================================================>
        for (int i = 1; i < dateAfterRemove.size(); i++) {
//            Date date=dateAfterRemove.get(i);
            String dateStr = dateAfterRemove.get(i);
            //入科时间  rkTimeStr
            //先判断 入科时间是处于哪个班次 根据时间范围计算 后一个统计的班次逻辑
//            A班统计时间:7:00:01-16:00:00（此处的A班统计的是7点-16点的数据）
//            P班统计时间:16:00:01-00:00:00（此处的P班统计的是16点-00点的数据）
//            N班统计时间：7:00:01-7:00：00为24小时出入量（此处的N班统计的是7点-7点的数据

//            Map noData = new LinkedHashMap();
//
//            noData.put("统计A班", "(9小时) 总入量:0ml;总出量:0ml;  ");
//            List<Map> mapNode = new ArrayList<>();
//            mapNode.add(noData);
//            mapData.put(dateStr + " 16:00:01#", mapNode);
//
//
//            Map mapGuDingP = new HashMap();
//            mapGuDingP.put("统计P班", "(8小时) 总入量:0ml;总出量:0ml;  ");
//            List<Map> mapNodeP = new ArrayList<>();
//            mapNodeP.add(mapGuDingP);
//
//            LocalDateTime localDateTime = LocalDateTime.ofInstant(DateUtil.parseDate(dateStr).toInstant(), zoneId);
//            LocalDateTime tomorrow = localDateTime.plusDays(1);
//            mapData.put(tomorrow.format(dateFormatter) + " 00:00:01#", mapNodeP);
//
//
//            Map mapGuDingN = new HashMap();
//            mapGuDingN.put("统计N班", " (24小时) 总入量:0ml;总出量:0ml;   ");
//            List<Map> mapNodeN = new ArrayList<>();
//            mapNodeN.add(mapGuDingN);
//
//            mapData.put(tomorrow.format(dateFormatter) + " 07:00:01#", mapNodeN);

            List<Map> mapNode = new ArrayList<>();
            List<Map> mapNode2 = new ArrayList<>();
            List<Map> mapNode3 = new ArrayList<>();

            // String dateStr = uniqueListHaveData.get(l);

            Date dateV = DateUtil.parseDate(dateStr);
            Calendar c = Calendar.getInstance();
            c.setTime(dateV);
            c.add(Calendar.DATE, 1);
            Date dateVAfter = c.getTime();
            String nextDay = DateUtil.formatDate(dateVAfter);

//            Calendar cFront = Calendar.getInstance();
//            c.setTime(dateV);
//            c.add(Calendar.DATE, -1);
//            Date dateVFront = c.getTime();
//            String frontDay = DateUtil.formatDate(dateVFront);


            //A班统计时间:7:00:01-16:00:00（此处的A班统计的是7点-16点的数据）
            //A班总入量 总出量
            BigDecimal inSumValueA = new BigDecimal(0);
            BigDecimal outSumValueA = new BigDecimal(0);


            // apn班 总入量 总出量统计
            List<IoModelVO> listModelCodeAll = bIoRecordMapper.selectSumOfModelAll(hospitalNumber, dateStr + " 07:00:01", dateStr + " 16:00:00",
                    dateStr + " 16:00:01", nextDay + " 00:00:00",
                    dateStr + " 07:00:01", nextDay + " 07:00:00", CommonConstant.YES_NUMBER);

            if (listModelCodeAll.size() > 0) {

                //由于产品设计的 时间范围 问题 导致 没有日期的那天数据 对应的班次 也会有数据 （比如30号的凌晨0点到7点 属于29号的n班 ，如果29号没数据会导致这段时间的数据统计不到 所以这边再单独查询统计下）
                List<IoModelVO> listModelCodeA = listModelCodeAll.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());

                IoModelVO firstIn = listModelCodeA.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
                if (null != firstIn) {
                    inSumValueA = firstIn.getSumValue();
                }

                IoModelVO firstOut = listModelCodeA.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
                if (null != firstOut) {
                    outSumValueA = firstOut.getSumValue();
                }

                //平衡量
                BigDecimal phl = inSumValueA.subtract(outSumValueA);


                //出量明细 统计信息
                StringBuilder stringBuilderInDetail;
                StringBuilder stringBuilderOutDetail;


                List<IoDetailVO> ioDetailVOListAll = bIoRecordMapper.selectSumOfDetailAll(hospitalNumber, dateStr + " 07:00:01", dateStr + " 16:00:00",
                        dateStr + " 16:00:01", nextDay + " 00:00:00",
                        dateStr + " 07:00:01", nextDay + " 07:00:00", CommonConstant.YES_NUMBER);
//                    frontDay + " 07:00:01", dateStr + " 07:00:00");


                List<IoDetailVO> ioDetailVOListA = ioDetailVOListAll.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());
                stringBuilderInDetail = getInContent(ioDetailVOListA);
                stringBuilderOutDetail = getOutContent(ioDetailVOListA);

                //A班
                Map map1 = new HashMap();
                map1.put("统计A班", "(9小时) 总入量:" + inSumValueA.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValueA.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

                List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get(dateStr + " 16:00:00" + "@" + patientIdent);
                if (CollectionUtils.isNotEmpty(listObsv)) {
                    Optional<BObsvRecord> result = listObsv.stream().findFirst();
                    if (result.isPresent()) {
                        String user = result.get().getCaijiren();
                        if (StrUtil.isNotEmpty(user)) {
                            map1.put("operator", user);
                        }
                    }
                }
                //P班统计时间:16:00:01-00:00:00（此处的P班统计的是16点-00点的数据）  ###################################################################################################

                //P班总入量 总出量
                BigDecimal inSumValueP = new BigDecimal(0);
                BigDecimal outSumValueP = new BigDecimal(0);

                List<IoModelVO> listModelCodeP = listModelCodeAll.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

                IoModelVO firstInP = listModelCodeP.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
                if (null != firstInP) {
                    inSumValueP = firstInP.getSumValue();
                }

                IoModelVO firstOutP = listModelCodeP.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
                if (null != firstOutP) {
                    outSumValueP = firstOutP.getSumValue();
                }

                phl = inSumValueP.subtract(outSumValueP);


                //P班入量明显选项 的统计信息
                StringBuilder stringBuilderInDetailP;
                StringBuilder stringBuilderOutDetailP;

                List<IoDetailVO> ioDetailVOListP = ioDetailVOListAll.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

//            stringBuilderInDetailP = getInContent(ioDetailVOListP);
                stringBuilderOutDetailP = getOutContent(ioDetailVOListP);

                //P班
                Map map2 = new HashMap();
                map2.put("统计P班", "(8小时) 总入量:" + inSumValueP.stripTrailingZeros().toPlainString() + "ml;" + ";总出量:" + outSumValueP.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetailP);
                //N班统计时间：7:00:01-7:00：00为24小时出入量（此处的N班统计的是7点-7点的数据）  ###################################################################################################
                //N班总入量 总出量
                BigDecimal inSumValueN = new BigDecimal(0);
                BigDecimal outSumValueN = new BigDecimal(0);


                List<IoModelVO> listModelCodeN = listModelCodeAll.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());

                IoModelVO firstInN = listModelCodeN.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
                if (null != firstInN) {
                    inSumValueN = firstInN.getSumValue();
                }

                IoModelVO firstOutN = listModelCodeN.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
                if (null != firstOutN) {
                    outSumValueN = firstOutN.getSumValue();
                }
                phl = inSumValueN.subtract(outSumValueN);

                //N班入量明显选项 的统计信息
                StringBuilder stringBuilderInDetailN;
                StringBuilder stringBuilderOutDetailN;

                List<IoDetailVO> ioDetailVOListN = ioDetailVOListAll.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());

//            stringBuilderInDetailN = getInContent(ioDetailVOListN);
                stringBuilderOutDetailN = getOutContent(ioDetailVOListN);

                //N班
                Map map3 = new HashMap();
                map3.put("统计班N班", "(24小时) 总入量:" + inSumValueN.stripTrailingZeros().toPlainString() + "ml;" + ";总出量:" + outSumValueN.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetailN);


                LocalDateTime localDateTime = LocalDateTime.ofInstant(dateV.toInstant(), zoneId);
                LocalDateTime tomorrow = localDateTime.plusDays(1);

                List<BObsvRecord> listObsvMap1 = collectsObsvMapForCaijiren.get(dateStr + " 16:00:00" + "@" + patientIdent);
                if (CollectionUtils.isNotEmpty(listObsvMap1)) {
                    Optional<BObsvRecord> result = listObsvMap1.stream().findFirst();
                    if (result.isPresent()) {
                        String user = result.get().getCaijiren();
                        if (StrUtil.isNotEmpty(user)) {
                            map1.put("operator", user);
                        }
                    }
                }
                List<BObsvRecord> listObsvMap2 = collectsObsvMapForCaijiren.get(tomorrow.format(dateFormatter) + " 00:00:00" + "@" + patientIdent);
                if (CollectionUtils.isNotEmpty(listObsvMap2)) {
                    Optional<BObsvRecord> result = listObsvMap2.stream().findFirst();
                    if (result.isPresent()) {
                        String user = result.get().getCaijiren();
                        if (StrUtil.isNotEmpty(user)) {
                            map2.put("operator", user);
                        }
                    }
                }
                List<BObsvRecord> listObsvMap3 = collectsObsvMapForCaijiren.get(tomorrow.format(dateFormatter) + " 07:00:00" + "@" + patientIdent);
                if (CollectionUtils.isNotEmpty(listObsvMap3)) {
                    Optional<BObsvRecord> result = listObsvMap3.stream().findFirst();
                    if (result.isPresent()) {
                        String user = result.get().getCaijiren();
                        if (StrUtil.isNotEmpty(user)) {
                            map3.put("operator", user);
                        }
                    }
                }
                mapNode.add(map1);
                mapNode2.add(map2);
                mapNode3.add(map3);
                //a班
                mapData.put(DateUtil.formatDate(dateV) + " 16:00:01#", mapNode);

                //p班
                mapData.put(tomorrow.format(dateFormatter) + " 00:00:01#", mapNode2);
                //n班
                mapData.put(tomorrow.format(dateFormatter) + " 07:00:01#", mapNode3);
            } else {
                //没有数据的
                Map noData = new LinkedHashMap();
//
                noData.put("统计A班", "(9小时) 总入量:0ml;总出量:0ml;  ");
                List<Map> mapNodeNoDataA = new ArrayList<>();
                mapNodeNoDataA.add(noData);
                mapData.put(dateStr + " 16:00:01#", mapNodeNoDataA);


                Map mapGuDingP = new HashMap();
                mapGuDingP.put("统计P班", "(8小时) 总入量:0ml;总出量:0ml;  ");
                List<Map> mapNodeP = new ArrayList<>();
                mapNodeP.add(mapGuDingP);

                LocalDateTime localDateTime = LocalDateTime.ofInstant(DateUtil.parseDate(dateStr).toInstant(), zoneId);
                LocalDateTime tomorrow = localDateTime.plusDays(1);
                mapData.put(tomorrow.format(dateFormatter) + " 00:00:01#", mapNodeP);


                Map mapGuDingN = new HashMap();
                mapGuDingN.put("统计N班", " (24小时) 总入量:0ml;总出量:0ml;   ");
                List<Map> mapNodeN = new ArrayList<>();
                mapNodeN.add(mapGuDingN);

                mapData.put(tomorrow.format(dateFormatter) + " 07:00:01#", mapNodeN);
            }
//                    frontDay + " 07:00:01", dateStr + " 07:00:00");


        }
        //<==============================================================================================================循环 没有数据的日期 结束

        Collections.sort(uniqueListHaveData);

        //有数据的 遍历统计    ================================================================================================================================================>
        for (int l = 0; l < uniqueListHaveData.size(); l++) {


            List<Map> mapNode = new ArrayList<>();
            List<Map> mapNode2 = new ArrayList<>();
            List<Map> mapNode3 = new ArrayList<>();

            String dateStr = uniqueListHaveData.get(l);

            Date dateV = DateUtil.parseDate(dateStr);
            Calendar c = Calendar.getInstance();
            c.setTime(dateV);
            c.add(Calendar.DATE, 1);
            Date dateVAfter = c.getTime();
            String nextDay = DateUtil.formatDate(dateVAfter);

            Calendar cFront = Calendar.getInstance();
            c.setTime(dateV);
            c.add(Calendar.DATE, -1);
            Date dateVFront = c.getTime();
            String frontDay = DateUtil.formatDate(dateVFront);


            //A班统计时间:7:00:01-16:00:00（此处的A班统计的是7点-16点的数据）
            //A班总入量 总出量
            BigDecimal inSumValueA = new BigDecimal(0);
            BigDecimal outSumValueA = new BigDecimal(0);


            // apn班 总入量 总出量统计
            List<IoModelVO> listModelCodeAll = bIoRecordMapper.selectSumOfModelAll(hospitalNumber, dateStr + " 07:00:01", dateStr + " 16:00:00",
                    dateStr + " 16:00:01", nextDay + " 00:00:00",
                    dateStr + " 07:00:01", nextDay + " 07:00:00", CommonConstant.YES_NUMBER);
//                    frontDay + " 07:00:01", dateStr + " 07:00:00");

            List<IoModelVO> listModelCodeA = listModelCodeAll.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());

            IoModelVO firstIn = listModelCodeA.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstIn) {
                inSumValueA = firstIn.getSumValue();
            }

            IoModelVO firstOut = listModelCodeA.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOut) {
                outSumValueA = firstOut.getSumValue();
            }

            //平衡量
            BigDecimal phl = inSumValueA.subtract(outSumValueA);


            //出量明细 统计信息
            StringBuilder stringBuilderInDetail;
            StringBuilder stringBuilderOutDetail;


            List<IoDetailVO> ioDetailVOListAll = bIoRecordMapper.selectSumOfDetailAll(hospitalNumber, dateStr + " 07:00:01", dateStr + " 16:00:00",
                    dateStr + " 16:00:01", nextDay + " 00:00:00",
                    dateStr + " 07:00:01", nextDay + " 07:00:00", CommonConstant.YES_NUMBER);
//                    frontDay + " 07:00:01", dateStr + " 07:00:00");


            List<IoDetailVO> ioDetailVOListA = ioDetailVOListAll.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());
            stringBuilderInDetail = getInContent(ioDetailVOListA);
            stringBuilderOutDetail = getOutContent(ioDetailVOListA);

            //A班
            Map map1 = new HashMap();
            map1.put("统计A班", "(9小时) 总入量:" + inSumValueA.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValueA.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

            List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get(dateStr + " 16:00:00" + "@" + patientIdent);
            if (CollectionUtils.isNotEmpty(listObsv)) {
                Optional<BObsvRecord> result = listObsv.stream().findFirst();
                if (result.isPresent()) {
                    String user = result.get().getCaijiren();
                    if (StrUtil.isNotEmpty(user)) {
                        map1.put("operator", user);
                    }
                }
            }
            //P班统计时间:16:00:01-00:00:00（此处的P班统计的是16点-00点的数据）  ###################################################################################################

            //P班总入量 总出量
            BigDecimal inSumValueP = new BigDecimal(0);
            BigDecimal outSumValueP = new BigDecimal(0);

            List<IoModelVO> listModelCodeP = listModelCodeAll.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

            IoModelVO firstInP = listModelCodeP.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstInP) {
                inSumValueP = firstInP.getSumValue();
            }

            IoModelVO firstOutP = listModelCodeP.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOutP) {
                outSumValueP = firstOutP.getSumValue();
            }

            phl = inSumValueP.subtract(outSumValueP);


            //P班入量明显选项 的统计信息
            StringBuilder stringBuilderInDetailP;
            StringBuilder stringBuilderOutDetailP;

            List<IoDetailVO> ioDetailVOListP = ioDetailVOListAll.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

//            stringBuilderInDetailP = getInContent(ioDetailVOListP);
            stringBuilderOutDetailP = getOutContent(ioDetailVOListP);

            //P班
            Map map2 = new HashMap();
            map2.put("统计P班", "(8小时) 总入量:" + inSumValueP.stripTrailingZeros().toPlainString() + "ml;" + ";总出量:" + outSumValueP.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetailP);
            //N班统计时间：7:00:01-7:00：00为24小时出入量（此处的N班统计的是7点-7点的数据）  ###################################################################################################
            //N班总入量 总出量
            BigDecimal inSumValueN = new BigDecimal(0);
            BigDecimal outSumValueN = new BigDecimal(0);


            List<IoModelVO> listModelCodeN = listModelCodeAll.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());

            IoModelVO firstInN = listModelCodeN.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
            if (null != firstInN) {
                inSumValueN = firstInN.getSumValue();
            }

            IoModelVO firstOutN = listModelCodeN.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
            if (null != firstOutN) {
                outSumValueN = firstOutN.getSumValue();
            }
            phl = inSumValueN.subtract(outSumValueN);

            //N班入量明显选项 的统计信息
            StringBuilder stringBuilderInDetailN;
            StringBuilder stringBuilderOutDetailN;

            List<IoDetailVO> ioDetailVOListN = ioDetailVOListAll.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());

//            stringBuilderInDetailN = getInContent(ioDetailVOListN);
            stringBuilderOutDetailN = getOutContent(ioDetailVOListN);

            //N班
            Map map3 = new HashMap();
            map3.put("统计班N班", "(24小时) 总入量:" + inSumValueN.stripTrailingZeros().toPlainString() + "ml;" + ";总出量:" + outSumValueN.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetailN);


            LocalDateTime localDateTime = LocalDateTime.ofInstant(dateV.toInstant(), zoneId);
            LocalDateTime tomorrow = localDateTime.plusDays(1);

            List<BObsvRecord> listObsvMap1 = collectsObsvMapForCaijiren.get(dateStr + " 16:00:00" + "@" + patientIdent);
            if (CollectionUtils.isNotEmpty(listObsvMap1)) {
                Optional<BObsvRecord> result = listObsvMap1.stream().findFirst();
                if (result.isPresent()) {
                    String user = result.get().getCaijiren();
                    if (StrUtil.isNotEmpty(user)) {
                        map1.put("operator", user);
                    }
                }
            }
            List<BObsvRecord> listObsvMap2 = collectsObsvMapForCaijiren.get(tomorrow.format(dateFormatter) + " 00:00:00" + "@" + patientIdent);
            if (CollectionUtils.isNotEmpty(listObsvMap2)) {
                Optional<BObsvRecord> result = listObsvMap2.stream().findFirst();
                if (result.isPresent()) {
                    String user = result.get().getCaijiren();
                    if (StrUtil.isNotEmpty(user)) {
                        map2.put("operator", user);
                    }
                }
            }
            List<BObsvRecord> listObsvMap3 = collectsObsvMapForCaijiren.get(tomorrow.format(dateFormatter) + " 07:00:00" + "@" + patientIdent);
            if (CollectionUtils.isNotEmpty(listObsvMap3)) {
                Optional<BObsvRecord> result = listObsvMap3.stream().findFirst();
                if (result.isPresent()) {
                    String user = result.get().getCaijiren();
                    if (StrUtil.isNotEmpty(user)) {
                        map3.put("operator", user);
                    }
                }
            }
            mapNode.add(map1);
            mapNode2.add(map2);
            mapNode3.add(map3);
            //a班
            mapData.put(DateUtil.formatDate(dateV) + " 16:00:01#", mapNode);

            //p班
            mapData.put(tomorrow.format(dateFormatter) + " 00:00:01#", mapNode2);
            //n班
            mapData.put(tomorrow.format(dateFormatter) + " 07:00:01#", mapNode3);


        }


        List<Map.Entry<String, List<Map>>> list = new ArrayList<>(mapData.entrySet());
        // 使用list.sort()排序，按key排序
        // 排序
        list.sort(Comparator.comparing(Map.Entry::getKey));

        //遍历删除
        boolean isRemove = false;
        Iterator<Map.Entry<String, List<Map>>> iterator = list.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<Map>> data = iterator.next();
            if (data.getKey().equals(resultEndTimeStr)) {
                isRemove = true;
                continue;
            }
            if (isRemove) {
                iterator.remove();//使用迭代器的删除方法删除
            }
        }


        //获取限制行数
        AtomicReference<Integer> recordNum = new AtomicReference<>(null);
        listCareRecordsConfig.forEach(e -> {
            BCareRecordsConfigNew po = e;

            //日期时间	date_value
            if (po.getDictValue().equals("date_value")) {
                Integer num = po.getRecordNum();

                recordNum.set(num);
            }
        });

        if (null != recordNum.get()) {
            //判断要截取值是否大于当前集合数  如果大于则使用当前集合长度
            if (list.size() < recordNum.get()) {
                recordNum.set(list.size());
            }
            //list集合截取
            List<Map.Entry<String, List<Map>>> listResult = list.subList(0, recordNum.get());
            //2022-02-08 00:00


            return listResult;
        } else {
            return list;
        }
    }

    /**
     * 出量明细
     *
     * @param ioDetailVOList
     * @return
     */
    public StringBuilder getOutContent(List<IoDetailVO> ioDetailVOList) {


        List<IoDetailVO> ioDetailListOut = ioDetailVOList.stream().filter(e -> e.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).collect(Collectors.toList());

        StringBuilder stringBuilderOutDetail = new StringBuilder();
        for (int i = 0; i < ioDetailListOut.size(); i++) {
            IoDetailVO ioDetailVO = ioDetailListOut.get(i);
            //隐藏等于0的明细
            if (ioDetailVO.getSumValue().compareTo(BigDecimal.ZERO) == 1 || ioDetailVO.getSumValue().compareTo(BigDecimal.ZERO) == -1) {
                stringBuilderOutDetail.append(ioDetailVO.getItemName() + ":" + ioDetailVO.getSumValue().stripTrailingZeros().toPlainString() + "ml");
            }

        }

        return stringBuilderOutDetail;
    }

    private static String fetchGroupKeyIoRecord(BIoRecord yxIoRecordPO) {
        return DateUtil.format(yxIoRecordPO.getRealTime(), "yyyy-MM-dd HH:mm:ss") + "@" + yxIoRecordPO.getUpdatedBy();
    }

    private static String fetchGroupKeyCrl(IoCodeDetailVO ioCodeDetailVO) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return ioCodeDetailVO.getRealTime().format(dateTimeFormatter) + "@" + ioCodeDetailVO.getUpdatedBy();
    }

    private static String fetchGroupKeyVte(BCarePgVte yxCarePgVtePO) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return yxCarePgVtePO.getPfTime().format(dateTimeFormatter) + "@" + yxCarePgVtePO.getUpdatedBy();
    }

    private static String fetchGroupKeyObsv(BObsvRecord obsvRecord) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return DateUtil.format(new Date(obsvRecord.getRecTime()), "yyyy-MM-dd HH:mm:ss") + "@" + obsvRecord.getPatientIdent();
    }


    /**
     * P班统计 信息
     *
     * @param listModelCodeAllOfRk
     * @param ioDetailVOListAllRk
     * @param dateNEnd
     * @param dateRk
     * @param patientIdent
     * @param collectsObsvMapForCaijiren
     * @return
     */
    public List<Map> getPOfSum(List<IoModelVO> listModelCodeAllOfRk, List<IoDetailVO> ioDetailVOListAllRk, Date dateNEnd, Date dateRk, String patientIdent, Map<String, List<BObsvRecord>> collectsObsvMapForCaijiren) {
        Map mapInit = new HashMap();

        //总入量
        BigDecimal inSumValue = new BigDecimal(0);
        BigDecimal outSumValue = new BigDecimal(0);

        List<IoModelVO> listModelCodeAOfRK = listModelCodeAllOfRk.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

        IoModelVO firstIn = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
        if (null != firstIn) {
            inSumValue = firstIn.getSumValue();
        }

        IoModelVO firstOut = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
        if (null != firstOut) {
            outSumValue = firstOut.getSumValue();
        }

        StringBuilder stringBuilderInDetail;
        StringBuilder stringBuilderOutDetail;


        List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllRk.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());
        stringBuilderInDetail = getInContent(ioDetailVOListA);
        stringBuilderOutDetail = getOutContent(ioDetailVOListA);

        //平衡量
        BigDecimal phl = inSumValue.subtract(outSumValue);

        mapInit.put("统计P班", "(8小时) 总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + ";总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

        List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get(YDateUtils.dateToDayStr(dateNEnd) + " 00:00:00" + "@" + patientIdent);
        if (CollectionUtils.isNotEmpty(listObsv)) {
            Optional<BObsvRecord> result = listObsv.stream().findFirst();
            if (result.isPresent()) {
                String user = result.get().getCaijiren();
                if (StrUtil.isNotEmpty(user)) {
                    mapInit.put("operator", user);
                }
            }
        }
        List<Map> mapNode = new ArrayList<>();
        mapNode.add(mapInit);
        return mapNode;
    }

    /**
     * 返回N班的统计数据
     *
     * @param listModelCodeAllOfRk
     * @param ioDetailVOListAllRk
     * @param dateNEnd
     * @param dateRk
     * @return
     */
    public List<Map> getNOfSum(List<IoModelVO> listModelCodeAllOfRk, List<IoDetailVO> ioDetailVOListAllRk, Date dateNEnd, Date dateRk, String patientIdent, Map<String, List<BObsvRecord>> collectsObsvMapForCaijiren) {
        Map mapInit = new HashMap();

        //总入量
        BigDecimal inSumValue = new BigDecimal(0);
        BigDecimal outSumValue = new BigDecimal(0);

        List<IoModelVO> listModelCodeAOfRK = listModelCodeAllOfRk.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());

        IoModelVO firstIn = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
        if (null != firstIn) {
            inSumValue = firstIn.getSumValue();
        }

        IoModelVO firstOut = listModelCodeAOfRK.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
        if (null != firstOut) {
            outSumValue = firstOut.getSumValue();
        }

        StringBuilder stringBuilderInDetail;
        StringBuilder stringBuilderOutDetail;


        List<IoDetailVO> ioDetailVOListA = ioDetailVOListAllRk.stream().filter(e -> e.getBanci().equals("N")).collect(Collectors.toList());
        stringBuilderInDetail = getInContent(ioDetailVOListA);
        stringBuilderOutDetail = getOutContent(ioDetailVOListA);

        //平衡量
        BigDecimal phl = inSumValue.subtract(outSumValue);


        mapInit.put("统计N班", " (" + YDateUtils.getDatePoor(dateNEnd, dateRk) + ")  总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);

        List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get(YDateUtils.dateToDayStr(dateNEnd) + " 07:00:00" + "@" + patientIdent);
        if (CollectionUtils.isNotEmpty(listObsv)) {
            Optional<BObsvRecord> result = listObsv.stream().findFirst();
            if (result.isPresent()) {
                String user = result.get().getCaijiren();
                if (StrUtil.isNotEmpty(user)) {
                    mapInit.put("operator", user);
                }
            }
        }
        List<Map> mapNode = new ArrayList<>();
        mapNode.add(mapInit);
        return mapNode;
    }

    /**
     * 入量明细
     *
     * @param ioDetailVOList
     * @return
     */
    public StringBuilder getInContent(List<IoDetailVO> ioDetailVOList) {


        List<IoDetailVO> ioDetailListIn = ioDetailVOList.stream().filter(e -> e.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).collect(Collectors.toList());

        BigDecimal kf = new BigDecimal(0);
        BigDecimal inBslkf = new BigDecimal(0);
        BigDecimal inKfywrl = new BigDecimal(0);
        BigDecimal jd = new BigDecimal(0);
        BigDecimal qt = new BigDecimal(0);
        BigDecimal sxzp = new BigDecimal(0);
        BigDecimal hl7sxzp = new BigDecimal(0);
        StringBuilder stringBuilderInDetail = new StringBuilder();
        for (int i = 0; i < ioDetailListIn.size(); i++) {
            IoDetailVO ioDetailVO = ioDetailListIn.get(i);
            //in_kf=in_bsl+ in_kfywrl+in_kf
            if (ioDetailVO.getItemCode().equals("in_kf")) {
                kf = ioDetailVO.getSumValue();
            } else if (ioDetailVO.getItemCode().equals("in_bsl")) {
                inBslkf = ioDetailVO.getSumValue();
            } else if (ioDetailVO.getItemCode().equals("in_kfywrl")) {
                inKfywrl = ioDetailVO.getSumValue();
            } else if (ioDetailVO.getItemCode().equals("in_jmrl")) {
                jd = ioDetailVO.getSumValue();
            } else if (ioDetailVO.getItemCode().equals("in_qt")) {
                qt = ioDetailVO.getSumValue();
            } else if (ioDetailVO.getItemCode().equals("in_sxzpl")) {
                sxzp = ioDetailVO.getSumValue();
            } else if (ioDetailVO.getItemCode().equals("in_hl7sxzpl")) {
                hl7sxzp = ioDetailVO.getSumValue();
            }


        }
        kf = kf.add(inBslkf);
        kf = kf.add(inKfywrl);
        jd = jd.add(sxzp);
        jd = jd.add(hl7sxzp);

        //隐藏等于0的明细
        if (jd.compareTo(BigDecimal.ZERO) == 1) {
            stringBuilderInDetail.append("静点:" + jd.stripTrailingZeros().toPlainString() + "ml ");
        }
        if (kf.compareTo(BigDecimal.ZERO) == 1) {
            stringBuilderInDetail.append("口服:" + kf.stripTrailingZeros().toPlainString() + "ml ");
        }
        if (qt.compareTo(BigDecimal.ZERO) == 1) {
            stringBuilderInDetail.append("其他:" + qt.stripTrailingZeros().toPlainString() + "ml ");
        }

        return stringBuilderInDetail;


    }


    /**
     * A班统计明细
     *
     * @param dateStr
     * @param hospitalNumber
     * @param nextDay
     * @param patientIdent
     * @param collectsObsvMapForCaijiren
     * @return
     */
    public List<Map> getListSumOfA(String dateStr, String hospitalNumber, String nextDay, String patientIdent, Map<String, List<BObsvRecord>> collectsObsvMapForCaijiren) {

        List<Map> mapNode = new ArrayList<>();
        //总入量
        BigDecimal inSumValue = new BigDecimal(0);
        BigDecimal outSumValue = new BigDecimal(0);

        //CareCommonUtil.addAndSubtractDaysByGetTime()
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Date frontDay = CareCommonUtil.addAndSubtractDaysByGetTime(date, -1);
        //A班 总入量 总出量统计
        List<IoModelVO> listModelCodeAll = bIoRecordMapper.selectSumOfModelAll(hospitalNumber, dateStr + " 07:00:01", dateStr + " 16:00:00",
                dateStr + " 16:00:01", nextDay + " 00:00:00",
                dateStr + " 07:00:01", nextDay + " 07:00:00", CommonConstant.YES_NUMBER);
//                frontDay + " 07:00:01", dateStr + " 07:00:00");


        List<IoModelVO> listModelCodeA = listModelCodeAll.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());

        IoModelVO firstIn = listModelCodeA.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
        if (null != firstIn) {
            inSumValue = firstIn.getSumValue();
        }

        IoModelVO firstOut = listModelCodeA.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
        if (null != firstOut) {
            outSumValue = firstOut.getSumValue();
        }

        //平衡量
        BigDecimal phl = inSumValue.subtract(outSumValue);


        //出量明细 统计信息
        StringBuilder stringBuilderInDetail;
        StringBuilder stringBuilderOutDetail;

        List<IoDetailVO> ioDetailVOListAll = bIoRecordMapper.selectSumOfDetailAll(hospitalNumber, dateStr + " 07:00:01", dateStr + " 16:00:00",
                dateStr + " 16:00:01", nextDay + " 00:00:00",
                dateStr + " 07:00:01", nextDay + " 07:00:00", CommonConstant.YES_NUMBER);
//                frontDay + " 07:00:01", dateStr + " 07:00:00");


        List<IoDetailVO> ioDetailVOListA = ioDetailVOListAll.stream().filter(e -> e.getBanci().equals("A")).collect(Collectors.toList());
        stringBuilderInDetail = getInContent(ioDetailVOListA);
        stringBuilderOutDetail = getOutContent(ioDetailVOListA);

        //A班
        Map map1 = new HashMap();
        map1.put("统计A班", "(9小时) 总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + "总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetail);
//        String user = yxObsvRecordMapper.selectUserByTime(patientIdent,YDateUtils.stringToDate(dateStr + " 16:00:00",YDateUtils.DATE_TIME_PATTERN).getTime());
//        if(StrUtil.isNotEmpty(user)){
//            map1.put("operator",user);
//        }
        List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get(dateStr + " 16:00:00" + "@" + patientIdent);
        if (CollectionUtils.isNotEmpty(listObsv)) {
            Optional<BObsvRecord> result = listObsv.stream().findFirst();
            if (result.isPresent()) {
                String user = result.get().getCaijiren();
                if (StrUtil.isNotEmpty(user)) {
                    map1.put("operator", user);
                }
            }
        }
        mapNode.add(map1);
        return mapNode;
    }


    public List<Map> getListSumOfP(String dateStr, String hospitalNumber, String nextDay, String patientIdent, Map<String, List<BObsvRecord>> collectsObsvMapForCaijiren) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Date frontDay = CareCommonUtil.addAndSubtractDaysByGetTime(date, -1);

        // apn班 总入量 总出量统计
        List<IoModelVO> listModelCodeAll = bIoRecordMapper.selectSumOfModelAll(hospitalNumber, dateStr + " 07:00:01", dateStr + " 16:00:00",
                dateStr + " 16:00:01", nextDay + " 00:00:00",
                dateStr + " 07:00:01", nextDay + " 07:00:00", CommonConstant.YES_NUMBER);
//                frontDay + " 07:00:01", dateStr + " 07:00:00");


        List<IoDetailVO> ioDetailVOListAll = bIoRecordMapper.selectSumOfDetailAll(hospitalNumber, dateStr + " 07:00:01", dateStr + " 16:00:00",
                dateStr + " 16:00:01", nextDay + " 00:00:00",
                dateStr + " 07:00:01", nextDay + " 07:00:00", CommonConstant.YES_NUMBER);
//                frontDay + " 07:00:01", dateStr + " 07:00:00");


        //总入量
        BigDecimal inSumValue = new BigDecimal(0);
        BigDecimal outSumValue = new BigDecimal(0);
        //平衡量
        BigDecimal phl;

        List<Map> mapNode2 = new ArrayList<>();

        List<IoModelVO> listModelCodeP = listModelCodeAll.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

        IoModelVO firstInP = listModelCodeP.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_IN)).findAny().orElse(null);
        if (null != firstInP) {
            inSumValue = firstInP.getSumValue();
        }

        IoModelVO firstOutP = listModelCodeP.stream().filter(item -> item.getModelCode().equals(ModelItemConstant.MODEL_CRL_OUT)).findAny().orElse(null);
        if (null != firstOutP) {
            outSumValue = firstOutP.getSumValue();
        }

        phl = inSumValue.subtract(outSumValue);


        //P班入量明显选项 的统计信息
        StringBuilder stringBuilderInDetailP;
        StringBuilder stringBuilderOutDetailP;

        List<IoDetailVO> ioDetailVOListP = ioDetailVOListAll.stream().filter(e -> e.getBanci().equals("P")).collect(Collectors.toList());

        stringBuilderInDetailP = getInContent(ioDetailVOListP);
        stringBuilderOutDetailP = getOutContent(ioDetailVOListP);

        //P班
        Map map2 = new HashMap();
        map2.put("统计P班", "(8小时) 总入量:" + inSumValue.stripTrailingZeros().toPlainString() + "ml;" + ";总出量:" + outSumValue.stripTrailingZeros().toPlainString() + "ml;" + stringBuilderOutDetailP);


        List<BObsvRecord> listObsv = collectsObsvMapForCaijiren.get(nextDay + " 00:00:00" + "@" + patientIdent);
        if (CollectionUtils.isNotEmpty(listObsv)) {
            Optional<BObsvRecord> result = listObsv.stream().findFirst();
            if (result.isPresent()) {
                String user = result.get().getCaijiren();
                if (StrUtil.isNotEmpty(user)) {
                    map2.put("operator", user);
                }
            }
        }
        mapNode2.add(map2);
        return mapNode2;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, TimePlanInVO> listofDataSave(CareRecordDataVO careRecordDataVO) {
        Map<String, TimePlanInVO> result = new HashMap<>();
        Long time = YDateUtils.strToDate(YDateUtils.format(new Date(careRecordDataVO.getRecordTime()),
                YDateUtils.DATE_TIME_MINUTE_PATTERN) + ":00", YDateUtils.DATE_TIME_PATTERN).getTime();
        //观察项配置
        List<BCareRecordsConfigNew> obsv = bCareRecordsConfigNewMapper.selectObsvCode();
        Set<String> obsvcodes = new HashSet<>();
        if (CollectionUtil.isNotEmpty(obsv)) {
            obsvcodes = obsv.stream().map(BCareRecordsConfigNew::getObsvCode).collect(Collectors.toSet());
        }
        //评估评分配置
        List<BCareRecordsConfigNew> pgs = bCareRecordsConfigNewMapper.selectPg();
        Set<Long> pgid = new HashSet<>();
        if (CollectionUtil.isNotEmpty(pgs)) {
            pgid = pgs.stream().map(BCareRecordsConfigNew::getPgId).collect(Collectors.toSet());
        }
        List<BPgpf> pgpfsall = bPgpfMapper.selectListByIds(pgid);
        Map<String, BPgpf> pgpfmap = pgpfsall.stream().collect(Collectors.toMap(BPgpf::getPgCode, Function.identity()));
        Set<Integer> vte = new HashSet<>();
//        if(pgpfmap.containsKey("pgpf_braden")){
//            vte.add(6);
//            pgpfmap.remove("pgpf_braden");
//        }

        //评估评分配置
        List<BCareRecordsConfigNew> barden = bCareRecordsConfigNewMapper.selectVteBarden();
        if (CollectionUtil.isNotEmpty(barden)) {
            vte.add(6);
        }

        //跌倒评分配置
        List<BCareRecordsConfigNew> vteadd = bCareRecordsConfigNewMapper.selectVteAdd();
        if (CollectionUtil.isNotEmpty(vteadd)) {
            vte.add(4);
        }
        Set<Long> pgpfs = pgpfmap.values().stream().map(BPgpf::getId).collect(Collectors.toSet());
        //护理操作配置
        List<BCareRecordsConfigNew> hlczs = bCareRecordsConfigNewMapper.selectHlcz();
        Set<String> hlczcodes = hlczs.stream().map(BCareRecordsConfigNew::getItemCode).collect(Collectors.toSet());

        Boolean iszhengdian = true;
        if ((time / 1000 / 60) % 60 != 0) {
            iszhengdian = false;
        }
        Date today = YDateUtils.strToDate(YDateUtils.dateToDayStr(new Date(time)) + " 00:00:00", YDateUtils.DATE_TIME_PATTERN);

        //批量保存观察项
        if (CollectionUtil.isNotEmpty(careRecordDataVO.getGcx()) && CollectionUtil.isNotEmpty(obsvcodes)) {
            if (iszhengdian == false) {
                TimePlanInVO inVO = new TimePlanInVO();
                inVO.setEndTime(YDateUtils.format(new Date(time), YDateUtils.TIME));
                inVO.setStartTime(YDateUtils.format(new Date(time), YDateUtils.TIME));
                inVO.setHospitalNumber(careRecordDataVO.getHospitalNumber());
                inVO.setAddDay(0);
                inVO.setCurrentDate(today.getTime());
                inVO.setPatientIdent(careRecordDataVO.getPatientIdent());
                inVO.setType("1");
                inVO.setCaijiren(careRecordDataVO.getOperator());
                inVO.setGh(careRecordDataVO.getAccount());
                inVO.setModuleId("yx-gcx");
                inVO.setInterval(1);
                result.put("yx-gcx", inVO);
            }
        }
        bObsvRecordService.careAddAndUpdate(careRecordDataVO.getGcx(), time, careRecordDataVO.getOperator(), careRecordDataVO.getAccount(), careRecordDataVO.getPatientIdent(), obsvcodes);
        //批量保存评估评分
        bPgRecordService.saveList(careRecordDataVO.getPg(), time, careRecordDataVO.getOperator(), careRecordDataVO.getAccount(), careRecordDataVO.getPatientIdent(), pgpfs);
        //批量保存评估评分vte
        bCarePgVteService.saveList(careRecordDataVO.getVte(), time, careRecordDataVO.getOperator(), careRecordDataVO.getPatientIdent(), vte);
        //批量护理操作
        if (CollectionUtil.isNotEmpty(careRecordDataVO.getHlcz())) {

            if (iszhengdian == false) {
                TimePlanInVO inVO = new TimePlanInVO();
                inVO.setEndTime(YDateUtils.format(new Date(time), YDateUtils.TIME));
                inVO.setStartTime(YDateUtils.format(new Date(time), YDateUtils.TIME));
                inVO.setHospitalNumber(careRecordDataVO.getHospitalNumber());
                inVO.setAddDay(0);
                inVO.setCurrentDate(today.getTime());
                inVO.setPatientIdent(careRecordDataVO.getPatientIdent());
                inVO.setType("1");
                inVO.setCaijiren(careRecordDataVO.getOperator());
                inVO.setGh(careRecordDataVO.getAccount());
                inVO.setModuleId("yx-hlcz");
                inVO.setInterval(1);
                result.put("yx-hlcz", inVO);

            }

            for (CareRecordQueryDto dto : careRecordDataVO.getHlcz()) {
                dto.setMappedTime(time);
            }
        }
        bCareRecordService.saveList(careRecordDataVO.getHlcz(), time, careRecordDataVO.getUserId(), careRecordDataVO.getPatientIdent(), hlczcodes);
        //批量保存出入量
        bIoRecordService.saveList(careRecordDataVO.getIo(), time, careRecordDataVO.getOperator(), careRecordDataVO.getAccount(), careRecordDataVO.getPatientIdent(), careRecordDataVO.getHospitalNumber());
        //批量护理记录
        if (CollectionUtil.isNotEmpty(careRecordDataVO.getHljl())) {
            for (BCareContent po : careRecordDataVO.getHljl()) {
                po.setRecordTime(YDateUtils.dateToLocalDateTime(new Date(time)));
                po.setRecordName(careRecordDataVO.getOperator());
                po.setRecordBy(String.valueOf(careRecordDataVO.getUserId()));
            }
        }
        bCareContentService.saveList(careRecordDataVO.getHljl(), time, careRecordDataVO.getPatientIdent(), careRecordDataVO.getOperator(), careRecordDataVO.getAccount(), careRecordDataVO.getUserId());
        return result;
    }


    @Override
    public CartPgpfTempOutVO listOfDataNewPgpfByTimeCode(String patientIdent, String hospitalNumber, Long recordTime, Long rkTime) {
        //评估评分配置
        CartPgpfTempOutVO result = new CartPgpfTempOutVO();
        List<BCareRecordsConfigNew> pgs = bCareRecordsConfigNewMapper.selectPg();
        Set<Long> pgid = new HashSet<>();
        if (CollectionUtil.isNotEmpty(pgs)) {
            pgid = pgs.stream().map(BCareRecordsConfigNew::getPgId).collect(Collectors.toSet());
        }
        List<BPgpf> pgpfsall = bPgpfMapper.selectListByIds(pgid);
        Map<String, BPgpf> pgpfmap = pgpfsall.stream().collect(Collectors.toMap(BPgpf::getPgCode, Function.identity()));
        Set<Integer> vte = new HashSet<>();
//        if(pgpfmap.containsKey("pgpf_braden")){
//            vte.add(6);
//            pgpfmap.remove("pgpf_braden");
//        }

        List<BCareRecordsConfigNew> barden = bCareRecordsConfigNewMapper.selectVteBarden();
        if (CollectionUtil.isNotEmpty(barden)) {
            vte.add(6);
        }

        //跌倒评分配置
        List<BCareRecordsConfigNew> vteadd = bCareRecordsConfigNewMapper.selectVteAdd();
        if (CollectionUtil.isNotEmpty(vteadd)) {
            vte.add(4);
        }
        Set<Long> pgpfs = pgpfmap.values().stream().map(BPgpf::getId).collect(Collectors.toSet());
        Map<Long, PgRecordVo> pgrecordmap = bPgRecordService.selectLatestByParams(patientIdent, hospitalNumber, pgpfs, recordTime, rkTime);
        Map<Integer, CarePgVteVO> vterecordmap = bCarePgVteService.selectLatestByParams(patientIdent, hospitalNumber, vte, recordTime, rkTime);
        Map<String, CarePgVteVO> vet = new HashMap<>();
        for (Map.Entry<Integer, CarePgVteVO> entry : vterecordmap.entrySet()) {
            if (entry.getKey() == 6) {
                vet.put("pgpf_braden", entry.getValue());
            } else if (entry.getKey() == 4) {
                vet.put("vte_dd", entry.getValue());
            }
        }
        result.setPg(pgrecordmap);
        result.setVte(vet);
        return result;
    }
}


